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, Deserialize, Serialize)]
373#[serde(deny_unknown_fields, default)]
374pub struct Graph {
375 #[serde(rename = "editing_network", skip_serializing)]
379 pub retired_editing_network: Option<serde::de::IgnoredAny>,
380 pub github_text_guard: bool,
382 pub github_language: String,
388 #[serde(alias = "candidates")]
420 pub implementers: usize,
421 #[serde(default)]
423 pub selected_implementer: Option<String>,
424 pub judges: usize,
426 pub deliberate_rounds: usize,
428 pub reviewers: usize,
436 pub review_rounds: usize,
438 pub gate_fix_rounds: usize,
444 pub max_parallel: usize,
446 pub language: String,
448 pub sessions: bool,
456 pub timeout_implement: u64,
458 pub timeout_judge: u64,
460 pub timeout_review: u64,
462 pub timeout_verify: Option<u64>,
471 pub timeout_fix: u64,
473 pub timeout_talk: u64,
481 pub timeout_resource_wait: u64,
490 pub retries: usize,
492 pub worktree_root: Option<PathBuf>,
494 pub land: bool,
507 pub land_rounds: usize,
509 pub rerun_flaky_checks: bool,
517 pub land_approval: bool,
528 pub hold_contested_merge: bool,
539 pub question_routing: bool,
544 pub file_followups: bool,
551 pub release_deputy_followups: bool,
559 pub answer_timeout: u64,
563 pub incomplete_review: IncompleteReviewPolicy,
566 pub e2e_every_round: bool,
584 pub advise: bool,
598 pub advisors: usize,
603 pub graft_runner_up: bool,
612}
613
614impl Default for Graph {
615 fn default() -> Self {
616 Self {
617 github_text_guard: true,
618 github_language: "en".into(),
619 implementers: 1,
620 selected_implementer: None,
621 retired_editing_network: None,
622 judges: 3,
623 deliberate_rounds: 1,
624 reviewers: 3,
625 review_rounds: 6,
626 gate_fix_rounds: 1,
627 max_parallel: 4,
628 language: "en".to_owned(),
629 sessions: true,
630 timeout_implement: 3600,
631 timeout_judge: 1200,
632 timeout_review: 1200,
633 timeout_verify: None,
634 timeout_fix: 1800,
635 timeout_talk: 3600,
636 timeout_resource_wait: 1800,
637 retries: 1,
638 worktree_root: None,
639 land: true,
640 land_rounds: 4,
641 rerun_flaky_checks: true,
642 land_approval: true,
643 hold_contested_merge: true,
644 question_routing: true,
645 file_followups: true,
646 release_deputy_followups: true,
647 answer_timeout: 86_400,
648 incomplete_review: IncompleteReviewPolicy::Block,
649 e2e_every_round: false,
650 advise: true,
651 advisors: 3,
652 graft_runner_up: true,
653 }
654 }
655}
656
657impl Graph {
658 pub fn verify_timeout(&self) -> u64 {
662 self.timeout_verify.unwrap_or(self.timeout_review)
663 }
664
665 pub fn language_gate(&self) -> bool {
668 self.github_text_guard && self.github_english()
669 }
670
671 pub fn github_english(&self) -> bool {
673 crate::lang::is_english(&self.github_language)
674 }
675}
676
677#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
684#[serde(rename_all = "lowercase")]
685pub enum IncompleteReviewPolicy {
686 Block,
690 Warn,
695}
696
697#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
699#[serde(rename_all = "lowercase")]
700pub enum LeakPolicy {
701 Warn,
703 Redact,
705 Fail,
707}
708
709#[derive(Debug, Clone, Deserialize, Serialize)]
716#[serde(deny_unknown_fields, default)]
717pub struct Blind {
718 pub commit_msg_hook: bool,
721 pub strip_lines: Vec<String>,
725 pub vendor_tokens: Vec<String>,
727 pub on_leak: LeakPolicy,
729 pub seed: Option<u64>,
732}
733
734impl Default for Blind {
735 fn default() -> Self {
736 Self {
737 commit_msg_hook: true,
738 strip_lines: [
739 "Co-Authored-By:",
740 "Signed-off-by:",
741 "Assisted-by:",
742 "Generated-by:",
743 "Generated with",
744 "\u{1f916}",
745 ]
746 .iter()
747 .map(|s| (*s).to_owned())
748 .collect(),
749 vendor_tokens: [
750 "claude",
751 "anthropic",
752 "codex",
753 "openai",
754 "chatgpt",
755 "gemini",
756 "grok",
757 "xai",
758 "copilot",
759 "opencode",
760 "qoder",
761 "cursor",
762 "\u{1f916}",
763 ]
764 .iter()
765 .map(|s| (*s).to_owned())
766 .collect(),
767 on_leak: LeakPolicy::Warn,
768 seed: None,
769 }
770 }
771}
772
773#[derive(Debug, Clone, Default, Deserialize, Serialize)]
775#[serde(deny_unknown_fields, default)]
776pub struct Verify {
777 pub e2e: Vec<String>,
780 pub gate: Vec<String>,
782 #[serde(default)]
791 pub pre_gate: Vec<String>,
792 pub shell: Option<Vec<String>>,
795}
796
797impl Verify {
798 pub fn cache_dir(&self) -> Option<PathBuf> {
804 self.e2e
805 .iter()
806 .chain(self.gate.iter())
807 .find_map(|cmd| crate::disk::extract_cargo_target_dir(cmd))
808 }
809
810 pub fn cargo_manifests(&self) -> Vec<PathBuf> {
813 let all: Vec<String> = self.e2e.iter().chain(self.gate.iter()).cloned().collect();
814 crate::cache::extract_manifest_paths(&all)
815 }
816}
817
818#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
820#[serde(deny_unknown_fields, default)]
821pub struct Worktree {
822 pub setup: Vec<SetupStep>,
825 pub pre_clean: Vec<PreCleanStep>,
827}
828
829#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
831#[serde(deny_unknown_fields)]
832pub struct PreCleanStep {
833 pub run: String,
835 pub timeout_secs: Option<u64>,
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.pre_clean.iter().enumerate() {
859 if step.run.trim().is_empty() || step.timeout_secs == Some(0) {
860 bail!(
861 "[worktree] pre_clean step {} requires a nonempty run and positive timeout",
862 i + 1
863 );
864 }
865 }
866 for (i, step) in self.setup.iter().enumerate() {
867 let n = i + 1;
868 match (&step.copy, &step.run) {
869 (Some(c), None) => {
870 if step.timeout_secs.is_some() {
871 bail!("[worktree] setup step {n}: `timeout_secs` applies to `run` only");
872 }
873 crate::worktree_setup::validate_copy(c)
874 .with_context(|| format!("[worktree] setup step {n}"))?;
875 }
876 (None, Some(r)) => {
877 if r.trim().is_empty() {
878 bail!("[worktree] setup step {n}: `run` is empty");
879 }
880 if step.optional {
881 bail!("[worktree] setup step {n}: `optional` applies to `copy` only");
882 }
883 }
884 _ => bail!("[worktree] setup step {n} must set exactly one of `copy` and `run`"),
885 }
886 }
887 Ok(())
888 }
889}
890
891#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
901#[serde(deny_unknown_fields, default)]
902pub struct Disk {
903 pub min_free_bytes: u64,
912 pub auto_fold: bool,
918 pub fold_grace_secs: u64,
926 pub cache_limit_bytes: u64,
938 pub worktree_limit_bytes: u64,
940 pub worktree_reclaim_bytes: u64,
944 pub retained_attempt_limit: usize,
948}
949
950impl Default for Disk {
951 fn default() -> Self {
952 Self {
953 min_free_bytes: 8 * 1024 * 1024 * 1024,
954 auto_fold: true,
955 fold_grace_secs: 6 * 60 * 60,
956 cache_limit_bytes: 10 * 1024 * 1024 * 1024,
957 worktree_limit_bytes: 10 * 1024 * 1024 * 1024,
958 worktree_reclaim_bytes: 16 * 1024 * 1024 * 1024,
959 retained_attempt_limit: 8,
960 }
961 }
962}
963
964#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
966#[serde(rename_all = "lowercase")]
967pub enum MergeMode {
968 None,
971 Local,
974 Pr,
978}
979
980#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
994#[serde(rename_all = "lowercase")]
995pub enum MergeStyle {
996 #[default]
1001 Merge,
1002 Squash,
1008 Rebase,
1014}
1015
1016#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1018#[serde(rename_all = "lowercase")]
1019pub enum MergeCi {
1020 #[default]
1022 Expected,
1023 None,
1025}
1026
1027impl MergeCi {
1028 pub fn expectation(self) -> crate::land::CiExpectation {
1030 match self {
1031 Self::Expected => crate::land::CiExpectation::Expected,
1032 Self::None => crate::land::CiExpectation::Absent,
1033 }
1034 }
1035}
1036
1037#[derive(Debug, Clone, Deserialize, Serialize)]
1039#[serde(deny_unknown_fields, default)]
1040pub struct Merge {
1041 pub mode: MergeMode,
1044 pub ci: MergeCi,
1046 pub base: Option<String>,
1048 pub style: MergeStyle,
1051 pub remote: String,
1053 pub release_bump: bool,
1066}
1067
1068impl Default for Merge {
1069 fn default() -> Self {
1070 Self {
1071 mode: MergeMode::None,
1072 ci: MergeCi::Expected,
1073 base: None,
1074 style: MergeStyle::default(),
1075 remote: "origin".to_owned(),
1076 release_bump: true,
1077 }
1078 }
1079}
1080
1081#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1083#[serde(rename_all = "lowercase")]
1084pub enum UpdateMode {
1085 Off,
1087 Notify,
1090 Install,
1092}
1093
1094#[derive(Debug, Clone, Deserialize, Serialize)]
1096#[serde(deny_unknown_fields, default)]
1097pub struct Update {
1098 pub mode: UpdateMode,
1100 pub interval: Option<String>,
1102 pub auto_restart: bool,
1104}
1105
1106impl Default for Update {
1107 fn default() -> Self {
1108 Self {
1109 mode: UpdateMode::Notify,
1110 interval: None,
1111 auto_restart: false,
1112 }
1113 }
1114}
1115
1116#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1118#[serde(rename_all = "lowercase")]
1119pub enum ReleaseMode {
1120 #[default]
1123 Actions,
1124 Local,
1129}
1130
1131#[derive(Debug, Clone, Deserialize, Serialize)]
1133#[serde(deny_unknown_fields, default)]
1134pub struct Release {
1135 pub mode: ReleaseMode,
1138 pub commands: Vec<String>,
1145 pub timeout_minutes: u64,
1147 pub version_files: Vec<VersionFile>,
1155}
1156
1157#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1159#[serde(rename_all = "lowercase")]
1160pub enum VersionKind {
1161 Cargo,
1163 Json,
1165}
1166
1167#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
1169#[serde(deny_unknown_fields)]
1170pub struct VersionFile {
1171 pub path: String,
1173 pub kind: VersionKind,
1175}
1176
1177impl Default for Release {
1178 fn default() -> Self {
1179 Self {
1180 mode: ReleaseMode::Actions,
1181 commands: Vec::new(),
1182 timeout_minutes: 30,
1183 version_files: Vec::new(),
1184 }
1185 }
1186}
1187
1188impl Release {
1189 pub fn validate(&self) -> Result<()> {
1191 crate::release_manifest::validate(&self.version_files).context("[release] version_files")
1192 }
1193
1194 pub fn is_local(&self) -> bool {
1196 self.mode == ReleaseMode::Local
1197 }
1198}
1199
1200#[derive(Debug, Clone, Deserialize, Serialize)]
1202#[serde(try_from = "CoordinationFields")]
1203pub struct Coordination {
1204 pub contract_file: String,
1206 pub contract_token: String,
1208 pub lock_file: String,
1210}
1211
1212#[derive(Deserialize, Default)]
1213#[serde(deny_unknown_fields, default)]
1214struct CoordinationFields {
1215 contract_file: String,
1216 contract_token: String,
1217 lock_file: String,
1218}
1219
1220impl TryFrom<CoordinationFields> for Coordination {
1221 type Error = anyhow::Error;
1222
1223 fn try_from(fields: CoordinationFields) -> Result<Self> {
1224 for (key, name) in [
1225 ("coordination.contract_file", &fields.contract_file),
1226 ("coordination.lock_file", &fields.lock_file),
1227 ] {
1228 if name.trim().is_empty()
1229 || name != name.trim()
1230 || name == "."
1231 || name.contains("..")
1232 || name.contains(['/', '\\', ':', '\0'])
1233 {
1234 bail!(
1235 "{key} must be a plain file name inside the Git common directory (no separators or '..')"
1236 );
1237 }
1238 }
1239 let token = &fields.contract_token;
1240 if token.is_empty() || token.trim() != token || token.chars().any(char::is_control) {
1241 bail!(
1242 "coordination.contract_token must be a nonempty single-line token without surrounding whitespace"
1243 );
1244 }
1245 Ok(Self {
1246 contract_file: fields.contract_file,
1247 contract_token: fields.contract_token,
1248 lock_file: fields.lock_file,
1249 })
1250 }
1251}
1252
1253#[cfg(test)]
1254pub(crate) fn test_coordination() -> Option<Coordination> {
1255 Some(Coordination {
1256 contract_file: "updater.contract".into(),
1257 contract_token: "test-protocol-v1".into(),
1258 lock_file: "updater.lock".into(),
1259 })
1260}
1261
1262#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1264#[serde(deny_unknown_fields, default)]
1265pub struct Config {
1266 pub coordination: Option<Coordination>,
1268 pub agents: Vec<AgentSpec>,
1270 pub roles: Roles,
1272 pub graph: Graph,
1274 pub blind: Blind,
1276 pub verify: Verify,
1278 pub worktree: Worktree,
1280 pub disk: Disk,
1282 pub merge: Merge,
1284 pub update: Update,
1286 pub prompts: Prompts,
1288 pub notify: Notify,
1290 pub repos: Repos,
1293 pub talk: Talk,
1295 pub daemon: Daemon,
1297 pub release: Release,
1299 pub context_windows: BTreeMap<String, u64>,
1302}
1303
1304const BUILTIN_CONTEXT_WINDOWS: &[(&str, u64)] = &[
1314 ("claude-opus-4", 200_000),
1315 ("claude-sonnet-4", 200_000),
1316 ("claude-haiku-4", 200_000),
1317 ("claude-3", 200_000),
1318 ("opus", 200_000),
1319 ("sonnet", 200_000),
1320 ("haiku", 200_000),
1321 ("gpt-5", 400_000),
1322 ("gpt-4.1", 1_000_000),
1323 ("gpt-4o", 128_000),
1324 ("o3", 200_000),
1325 ("o4-mini", 200_000),
1326 ("gemini-2.5", 1_000_000),
1327 ("deepseek", 128_000),
1328];
1329
1330impl Config {
1331 pub fn context_window(&self, model: &str) -> Option<u64> {
1336 fn lookup<'a>(model: &str, entries: impl Iterator<Item = (&'a str, u64)>) -> Option<u64> {
1337 let mut best: Option<(usize, u64)> = None;
1338 for (key, window) in entries {
1339 if key == model {
1340 return Some(window);
1341 }
1342 if model.starts_with(key) && best.is_none_or(|(len, _)| key.len() > len) {
1343 best = Some((key.len(), window));
1344 }
1345 }
1346 best.map(|(_, w)| w)
1347 }
1348 lookup(
1349 model,
1350 self.context_windows.iter().map(|(k, w)| (k.as_str(), *w)),
1351 )
1352 .or_else(|| lookup(model, BUILTIN_CONTEXT_WINDOWS.iter().copied()))
1353 }
1354}
1355
1356#[derive(Debug, Clone, Deserialize, Serialize)]
1366#[serde(deny_unknown_fields, default)]
1367pub struct Daemon {
1368 pub max_concurrent_runs: usize,
1389 pub pause_for_interrupts: bool,
1405 pub max_deputies: usize,
1412 pub release_stall_minutes: u64,
1419}
1420
1421impl Default for Daemon {
1422 fn default() -> Self {
1423 Self {
1424 max_concurrent_runs: 1,
1425 pause_for_interrupts: false,
1426 max_deputies: 2,
1427 release_stall_minutes: 60,
1428 }
1429 }
1430}
1431
1432#[derive(Debug, Clone, Deserialize, Serialize)]
1444#[serde(deny_unknown_fields, default)]
1445pub struct Repos {
1446 pub roots: Vec<PathBuf>,
1450 pub auto_clone: bool,
1452 pub clone_command: Option<Vec<String>>,
1456 pub scan_ttl: u64,
1463 pub fetch_interval: u64,
1468}
1469
1470impl Default for Repos {
1471 fn default() -> Self {
1472 Self {
1473 roots: Vec::new(),
1474 auto_clone: false,
1475 clone_command: None,
1476 scan_ttl: 86_400,
1477 fetch_interval: 600,
1478 }
1479 }
1480}
1481
1482#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1498#[serde(deny_unknown_fields, default)]
1499pub struct Prompts {
1500 pub all: String,
1502 pub implement: String,
1504 pub judge: String,
1506 pub review: String,
1508 pub fix: String,
1510}
1511
1512impl Prompts {
1513 pub fn overlay(&self, node: &str) -> Option<String> {
1518 let specific = match node {
1519 "implement" => &self.implement,
1520 "judge" | "vote" | "deliberate" => &self.judge,
1521 "review" => &self.review,
1522 "fix" => &self.fix,
1523 _ => "",
1524 };
1525 let mut parts: Vec<&str> = Vec::new();
1526 for p in [self.all.trim(), specific.trim()] {
1527 if !p.is_empty() {
1528 parts.push(p);
1529 }
1530 }
1531 if parts.is_empty() {
1532 return None;
1533 }
1534 Some(parts.join("\n\n"))
1535 }
1536}
1537
1538#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1545#[serde(deny_unknown_fields, default)]
1546pub struct Notify {
1547 pub command: Vec<String>,
1550}
1551
1552#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1554#[serde(deny_unknown_fields, default)]
1555pub struct Talk {
1556 pub allow_write: bool,
1565 pub personas: Vec<PersonaSpec>,
1570 pub operator_name: Option<String>,
1574}
1575
1576pub const OPERATOR_NAME_MAX: usize = 64;
1578
1579impl Talk {
1580 pub fn operator_name(&self) -> Option<&str> {
1582 self.operator_name
1583 .as_deref()
1584 .map(str::trim)
1585 .filter(|n| !n.is_empty())
1586 }
1587}
1588
1589#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
1591#[serde(deny_unknown_fields)]
1592pub struct PersonaSpec {
1593 pub id: String,
1595 #[serde(default)]
1598 pub name: String,
1599 #[serde(default)]
1602 pub prompt: String,
1603 #[serde(default, skip_serializing_if = "Option::is_none")]
1607 pub icon: Option<String>,
1608}
1609
1610#[derive(Debug, Clone)]
1612pub struct ResolvedRoles {
1613 pub implementers: Vec<AgentSpec>,
1615 pub judges: Vec<AgentSpec>,
1617 pub reviewers: Vec<AgentSpec>,
1619 pub fixer: Option<Vec<AgentSpec>>,
1624 pub conductor: AgentSpec,
1626 pub implementer_roster: Vec<AgentSpec>,
1634 pub judge_roster: Vec<AgentSpec>,
1638 pub reviewer_roster: Vec<AgentSpec>,
1640}
1641
1642fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
1649 let mut out = Vec::new();
1650 for (k, v) in table {
1651 if prefix.is_empty() && k == "vars" {
1652 continue;
1653 }
1654 let path = if prefix.is_empty() {
1655 k.clone()
1656 } else {
1657 format!("{prefix}.{k}")
1658 };
1659 match v {
1660 toml::Value::Array(_) => out.push(path),
1661 toml::Value::Table(t) => out.extend(array_keys(t, &path)),
1662 _ => {}
1663 }
1664 }
1665 out
1666}
1667
1668#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1670enum ArrayMerge {
1671 Append,
1675 Replace,
1678}
1679
1680fn array_merge_policy(key: &str) -> ArrayMerge {
1719 match key {
1720 "verify.e2e" | "verify.gate" | "verify.pre_gate" | "repos.roots" => ArrayMerge::Append,
1721 _ => ArrayMerge::Replace,
1722 }
1723}
1724
1725impl Config {
1726 pub fn load(path: &Path) -> Result<Self> {
1729 Self::load_layers(&[path.to_path_buf()])
1730 }
1731
1732 fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
1742 let mut ctx = teravars::system_context();
1743 let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
1744 ctx.insert("env", &env);
1745 if let Some(last) = paths.last()
1746 && let Some(dir) = last.parent()
1747 {
1748 let dir = std::fs::read_to_string(dir.join(REPO_MARKER))
1751 .map(|s| PathBuf::from(s.trim()))
1752 .unwrap_or_else(|_| dir.to_path_buf());
1753 ctx.insert("repo", &dir.to_string_lossy());
1754 ctx.insert(
1755 "repo_name",
1756 &dir.file_name().unwrap_or_default().to_string_lossy(),
1757 );
1758 }
1759 ctx
1760 }
1761
1762 pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
1770 let mut engine = teravars::Engine::default();
1771 let ctx = Self::render_ctx(paths);
1772 if paths.len() > 1 {
1773 Self::refuse_split_arrays(paths, &mut engine, &ctx).map_err(|error| {
1774 if error.downcast_ref::<ConfigFailure>().is_some() {
1775 error
1776 } else {
1777 let message = error.to_string();
1780 error
1781 .context(ConfigFailure::layers("config-merge", paths))
1782 .context(message)
1783 }
1784 })?;
1785 }
1786 let merged = teravars::load_merged(paths, &mut engine, &ctx)
1787 .map_err(|error| {
1788 let cause = ConfigFailure::render(&error, paths);
1789 anyhow::Error::new(error).context(cause)
1790 })
1791 .with_context(|| {
1792 format!(
1793 "rendering config via teravars: {}",
1794 paths
1795 .iter()
1796 .map(|p| p.display().to_string())
1797 .collect::<Vec<_>>()
1798 .join(", ")
1799 )
1800 })?;
1801 let mut table = merged.config;
1802 Self::normalize_renamed_keys(paths, &mut engine, &ctx, &mut table)?;
1803 table.remove("vars");
1806 let detect_agents = !table.contains_key("agents");
1810 let mut cfg: Self = toml::Value::Table(table)
1811 .try_into()
1812 .context("deserializing magi config")
1813 .context(ConfigFailure::layers("config-deserialize", paths))?;
1814 crate::persona::validate(&cfg.talk.personas)?;
1815 cfg.worktree.validate()?;
1816 cfg.release.validate()?;
1817 if let Some(name) = cfg.talk.operator_name() {
1818 if name.chars().count() > OPERATOR_NAME_MAX || name.chars().any(char::is_control) {
1819 bail!(
1820 "[talk] operator_name must be one line of at most {OPERATOR_NAME_MAX} characters"
1821 );
1822 }
1823 }
1824 if detect_agents {
1825 cfg.agents = Self::autodetected().agents;
1826 }
1827 Ok(cfg)
1828 }
1829
1830 fn normalize_renamed_keys(
1838 paths: &[PathBuf],
1839 engine: &mut teravars::Engine,
1840 ctx: &teravars::Context,
1841 table: &mut toml::map::Map<String, toml::Value>,
1842 ) -> Result<()> {
1843 let both = matches!(
1844 table.get("graph"),
1845 Some(toml::Value::Table(g)) if g.contains_key("candidates") && g.contains_key("implementers")
1846 );
1847 if !both {
1848 return Ok(());
1849 }
1850 let mut winner: Option<toml::Value> = None;
1851 for path in paths {
1852 let one = teravars::load_merged([path], engine, ctx)
1853 .map_err(|error| {
1854 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
1855 anyhow::Error::new(error).context(cause)
1856 })
1857 .with_context(|| format!("rendering {}", path.display()))?;
1858 let Some(toml::Value::Table(g)) = one.config.get("graph") else {
1859 continue;
1860 };
1861 if g.contains_key("candidates") && g.contains_key("implementers") {
1862 bail!(
1863 "`[graph]` sets both `implementers` and its deprecated alias \n `candidates` in {}; keep only `implementers`.",
1864 path.display()
1865 );
1866 }
1867 if let Some(v) = g.get("implementers").or_else(|| g.get("candidates")) {
1868 winner = Some(v.clone());
1869 }
1870 }
1871 if let Some(toml::Value::Table(g)) = table.get_mut("graph") {
1872 g.remove("candidates");
1873 if let Some(v) = winner {
1874 g.insert("implementers".to_owned(), v);
1875 }
1876 }
1877 Ok(())
1878 }
1879
1880 fn refuse_split_arrays(
1904 paths: &[PathBuf],
1905 engine: &mut teravars::Engine,
1906 ctx: &teravars::Context,
1907 ) -> Result<()> {
1908 let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
1909 for path in paths {
1910 let one = teravars::load_merged([path], engine, ctx)
1911 .map_err(|error| {
1912 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
1913 anyhow::Error::new(error).context(cause)
1914 })
1915 .with_context(|| format!("rendering {}", path.display()))?;
1916 for key in array_keys(&one.config, "") {
1917 if array_merge_policy(&key) == ArrayMerge::Append {
1918 continue;
1919 }
1920 if let Some(first) = seen.get(&key) {
1921 bail!(
1922 "`{key}` is an array declared in two config layers:\n \
1923 {}\n {}\nteravars appends arrays when it merges, so \
1924 magi would run the concatenation of both - which is \
1925 not what either file says. Declare `{key}` in exactly \
1926 one of them.",
1927 first.display(),
1928 path.display()
1929 );
1930 }
1931 seen.insert(key, path.clone());
1932 }
1933 }
1934 Ok(())
1935 }
1936
1937 pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
1959 let mut engine = teravars::Engine::default();
1960 let ctx = Self::render_ctx(paths);
1961 let mut out = Vec::new();
1962 for path in paths {
1963 let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
1964 continue;
1965 };
1966 let mut cur = &one.config;
1967 let mut found = None;
1968 let parts: Vec<&str> = key.split('.').collect();
1969 for (i, part) in parts.iter().enumerate() {
1970 match cur.get(*part) {
1971 Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
1972 found = Some(a);
1973 break;
1974 }
1975 Some(toml::Value::Table(t)) => cur = t,
1976 _ => break,
1977 }
1978 }
1979 let Some(values) = found else { continue };
1980 let strings: Vec<String> = values
1981 .iter()
1982 .filter_map(|v| v.as_str().map(str::to_owned))
1983 .collect();
1984 if !strings.is_empty() {
1985 out.push((path.clone(), strings));
1986 }
1987 }
1988 out
1989 }
1990
1991 pub(crate) fn layer_tables(paths: &[PathBuf]) -> Vec<(PathBuf, Result<toml::Table>)> {
1997 let mut engine = teravars::Engine::default();
1998 let ctx = Self::render_ctx(paths);
1999 paths
2000 .iter()
2001 .map(|path| {
2002 let one = teravars::load_merged([path], &mut engine, &ctx)
2003 .map(|m| m.config)
2004 .with_context(|| format!("rendering {}", path.display()));
2005 (path.clone(), one)
2006 })
2007 .collect()
2008 }
2009
2010 pub fn describe_composed(
2020 paths: &[PathBuf],
2021 commands: &[String],
2022 key: &str,
2023 empty: &str,
2024 ) -> String {
2025 if commands.is_empty() {
2026 return empty.to_owned();
2027 }
2028 let joined = commands.join(" && ");
2029 let provenance = Self::array_provenance(paths, key);
2030 if provenance.len() <= 1 {
2031 return joined;
2032 }
2033 let mut out = joined;
2034 for (path, cmds) in &provenance {
2035 out.push_str(&format!("\n [{}] {}", path.display(), cmds.join(" && ")));
2036 }
2037 out
2038 }
2039
2040 pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
2047 #[cfg(test)]
2048 crate::web::request_cost::discovery();
2049 if let Some(p) = explicit {
2050 let paths = vec![p.to_path_buf()];
2051 return Ok((Self::load_layers(&paths)?, paths));
2052 }
2053 let paths = Self::layers_checked(repo)?;
2054 if paths.is_empty() {
2055 return Ok((Self::autodetected(), paths));
2056 }
2057 Ok((Self::load_layers(&paths)?, paths))
2058 }
2059
2060 pub async fn discover_fetched(
2063 repo: &Path,
2064 explicit: Option<&Path>,
2065 ) -> Result<(Self, Vec<PathBuf>)> {
2066 if explicit.is_none() && is_git_worktree(repo) {
2067 let (remote, cfg_base) = probe_remote_base(repo);
2071 let base = crate::git::merge_base_branch(repo, &remote, cfg_base.as_deref())
2072 .await
2073 .with_context(|| ConfigFailure {
2074 stage: "config-base",
2075 target: remote.clone(),
2076 })?;
2077 let out = crate::git::fetch(repo, &remote, &base)
2078 .await
2079 .with_context(|| format!("fetching {remote}/{base} to read magi.toml"))
2080 .with_context(|| ConfigFailure {
2081 stage: "config-fetch",
2082 target: format!("{remote}/{base}"),
2083 })?;
2084 if !out.ok() {
2085 return Err(anyhow::anyhow!(
2086 "cannot read magi.toml: `git fetch {remote} {base}` failed ({}); refusing to use the local checkout's copy, which may be stale",
2087 out.stderr.lines().next().unwrap_or("").trim()
2088 )).context(ConfigFailure { stage: "config-fetch", target: format!("{remote}/{base}") });
2089 }
2090 if cfg_base.is_none() {
2091 crate::git::ensure_remote_head(repo, &remote, &base).await;
2092 }
2093 }
2094 Self::discover(repo, explicit).map_err(|error| {
2095 if error.downcast_ref::<ConfigFailure>().is_some() {
2096 error
2097 } else {
2098 error.context(ConfigFailure {
2099 stage: "config-load",
2100 target: explicit.unwrap_or(repo).to_string_lossy().into_owned(),
2101 })
2102 }
2103 })
2104 }
2105
2106 fn layers_checked(repo: &Path) -> Result<Vec<PathBuf>> {
2108 if !is_git_worktree(repo) {
2109 return Ok(Self::layers(repo));
2110 }
2111 let mut paths: Vec<PathBuf> = Self::machine_layer()
2112 .into_iter()
2113 .filter(|p| p.is_file())
2114 .collect();
2115 paths.extend(Self::repo_layers(repo)?);
2116 Ok(paths)
2117 }
2118
2119 pub(crate) fn repo_layer_description(repo: &Path, path: &Path) -> String {
2121 let cached = path.ancestors().find(|p| p.join(REPO_MARKER).is_file());
2122 if let Some(root) = cached {
2123 let relative = path.strip_prefix(root).unwrap_or(path);
2124 let reference = resolve_remote_base(repo)
2125 .map(|(remote, base)| format!("{remote}/{base}"))
2126 .unwrap_or_else(|_| "remote base".to_owned());
2127 format!(
2128 "{} at {reference} (including its includes)",
2129 repo.join(relative).display()
2130 )
2131 } else {
2132 format!("{} (including its includes)", path.display())
2133 }
2134 }
2135
2136 pub(crate) fn repo_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2139 if !is_git_worktree(repo) {
2140 return Ok([
2141 repo.join(".magi").join("config.toml"),
2142 repo.join("magi.toml"),
2143 ]
2144 .into_iter()
2145 .filter(|p| p.is_file())
2146 .collect());
2147 }
2148 remote_layers(repo)
2149 }
2150
2151 pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
2171
2172 pub fn layers(repo: &Path) -> Vec<PathBuf> {
2177 let mut paths = Vec::new();
2178 paths.extend(Self::machine_layer());
2179 paths.push(repo.join(".magi").join("config.toml"));
2180 paths.push(repo.join("magi.toml"));
2181 paths.retain(|p| p.is_file());
2182 paths
2183 }
2184
2185 #[cfg(test)]
2192 pub(crate) fn machine_layer() -> Option<PathBuf> {
2193 std::env::var(Self::CONFIG_DIR_ENV)
2194 .ok()
2195 .filter(|dir| !dir.trim().is_empty())
2196 .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
2197 }
2198
2199 #[cfg(not(test))]
2201 pub(crate) fn machine_layer() -> Option<PathBuf> {
2202 match std::env::var(Self::CONFIG_DIR_ENV) {
2203 Ok(dir) if dir.trim().is_empty() => None,
2205 Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
2206 Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
2207 }
2208 }
2209
2210 pub fn autodetected() -> Self {
2212 let mut cfg = Self::default();
2213 for (kind, id, model) in [
2214 (AgentKind::Claude, "opus", Some("opus")),
2215 (AgentKind::Claude, "sonnet", Some("sonnet")),
2216 (AgentKind::Antigravity, "antigravity", None),
2217 (AgentKind::Opencode, "opencode", None),
2218 (AgentKind::Codex, "codex", None),
2219 (AgentKind::Omp, "omp", None),
2220 ] {
2221 if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
2222 cfg.agents.push(AgentSpec {
2223 id: id.to_owned(),
2224 kind,
2225 model: model.map(str::to_owned),
2226 command: Vec::new(),
2227 extra_args: Vec::new(),
2228 env: BTreeMap::new(),
2229 prompt_delivery: None,
2230 max_turn_secs: None,
2231 });
2232 }
2233 }
2234 cfg
2235 }
2236
2237 pub fn cache_dir(&self) -> Option<PathBuf> {
2240 self.verify.cache_dir()
2241 }
2242
2243 pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
2245 self.agents
2246 .iter()
2247 .find(|a| a.id == id)
2248 .with_context(|| format!("no agent with id `{id}` in the roster"))
2249 }
2250
2251 fn rotate(&self, ids: &[String], count: usize, offset: usize) -> Result<Vec<AgentSpec>> {
2258 let mut out = Vec::with_capacity(count);
2259 for i in 0..count {
2260 let spec = if ids.is_empty() {
2261 self.agents[(i + offset) % self.agents.len()].clone()
2262 } else {
2263 self.agent(&ids[i % ids.len()])?.clone()
2264 };
2265 out.push(spec);
2266 }
2267 Ok(out)
2268 }
2269
2270 fn full_roster(&self, ids: &[String]) -> Result<Vec<AgentSpec>> {
2277 if ids.is_empty() {
2278 Ok(self.agents.clone())
2279 } else {
2280 ids.iter().map(|id| self.agent(id).cloned()).collect()
2281 }
2282 }
2283
2284 pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
2291 if self.agents.is_empty() {
2292 bail!(
2293 "agent roster is empty: no agent CLI found on PATH and no \
2294 [[agents]] in the config. Run `magi init` to write a starter \
2295 magi.toml."
2296 );
2297 }
2298 let pinned = self
2299 .graph
2300 .selected_implementer
2301 .as_ref()
2302 .map(|id| self.agent(id).cloned())
2303 .transpose()?;
2304 Ok(ResolvedRoles {
2305 implementers: match &pinned {
2306 Some(agent) => vec![agent.clone()],
2307 None => self.rotate(&self.roles.implementers, self.graph.implementers, 0)?,
2308 },
2309 judges: self.rotate(&self.roles.judges, self.graph.judges, 1)?,
2310 reviewers: self.rotate(&self.roles.reviewers, self.graph.reviewers, 0)?,
2311 fixer: match self.roles.fixer.as_ref() {
2312 Some(choice) => Some(crate::agent::pick_chain(
2315 &self.agents,
2316 Some(choice),
2317 &|_| true,
2318 "fixer",
2319 )?),
2320 None => None,
2321 },
2322 conductor: match self.roles.conductor.as_ref().map(AgentChoice::ids) {
2327 Some(ids) if ids.len() == 1 => self.agent(ids[0])?.clone(),
2328 Some(ids) if !ids.is_empty() => ids
2331 .iter()
2332 .find_map(|id| self.agent(id).ok())
2333 .cloned()
2334 .with_context(|| {
2335 format!("[roles] conductor names no agent in the roster: {ids:?}")
2336 })?,
2337 _ => crate::agent::pick(&self.agents, None, &crate::agent::installed)
2342 .unwrap_or_else(|_| self.agents[0].clone()),
2343 },
2344 implementer_roster: match pinned {
2345 Some(agent) => vec![agent],
2346 None => self.full_roster(&self.roles.implementers)?,
2347 },
2348 judge_roster: self.full_roster(&self.roles.judges)?,
2349 reviewer_roster: self.full_roster(&self.roles.reviewers)?,
2350 })
2351 }
2352
2353 pub fn advisors(&self) -> Result<Vec<AgentSpec>> {
2375 if self.agents.is_empty() {
2376 bail!(
2377 "agent roster is empty: no agent CLI found on PATH and no \
2378 [[agents]] in the config. Run `magi init` to write a starter \
2379 magi.toml."
2380 );
2381 }
2382 if !self.roles.advisors.is_empty() {
2383 return self.rotate(&self.roles.advisors, self.graph.advisors, 0);
2384 }
2385 self.rotate(&self.roles.judges, self.graph.advisors, 1)
2386 }
2387
2388 pub fn advisor_roster(&self) -> Result<Vec<AgentSpec>> {
2392 if self.roles.advisors.is_empty() {
2393 self.full_roster(&self.roles.judges)
2394 } else {
2395 self.full_roster(&self.roles.advisors)
2396 }
2397 }
2398
2399 pub fn shell(&self) -> Vec<String> {
2401 if let Some(s) = &self.verify.shell {
2402 return s.clone();
2403 }
2404 if which("sh") {
2405 vec!["sh".to_owned(), "-c".to_owned()]
2406 } else {
2407 vec!["cmd".to_owned(), "/C".to_owned()]
2408 }
2409 }
2410
2411 pub fn starter_toml() -> String {
2413 let detected = Self::autodetected();
2414 let mut s = String::from(
2415 "# magi — blind multi-agent implementation competition.\n\
2416 # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
2417 # -> blind judging -> deliberation -> private final vote\n\
2418 # -> fold losers -> review + E2E loop -> gate -> merge.\n\
2419 #\n\
2420 # Rendered by teravars: a `[vars]` table, env\n\
2421 # and system lookups, and `include = [...]` all work. Tera\n\
2422 # braces are live everywhere in this file, but comments are\n\
2423 # stripped before rendering (teravars >= 0.2.2), so a comment\n\
2424 # may quote `{{ ... }}` freely.\n\
2425 #\n\
2426 # Layers deep-merge in increasing\n\
2427 # precedence, so the roster can live once per machine in\n\
2428 # <config_dir>/magi/config.toml and each repo only states its own\n\
2429 # gate:\n\
2430 # <config_dir>/magi/config.toml < .magi/config.toml < magi.toml\n\n\
2431 [vars]\n\
2432 # Reference it as vars.cache inside Tera braces, anywhere below.\n\
2433 # Single quotes inside the braces: teravars renders the raw file\n\
2434 # text, so TOML's own \\\" escaping never reaches Tera.\n\
2435 cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
2436 );
2437 if detected.agents.is_empty() {
2438 s.push_str(
2439 "# No agent CLI was found on PATH. Fill this in by hand.\n\
2440 # kind = claude | opencode | antigravity | codex | command\n\
2441 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
2442 );
2443 } else {
2444 for a in &detected.agents {
2445 s.push_str("[[agents]]\n");
2446 s.push_str(&format!("id = {:?}\n", a.id));
2447 s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
2448 if let Some(m) = &a.model {
2449 s.push_str(&format!("model = {m:?}\n"));
2450 }
2451 s.push('\n');
2452 }
2453 }
2454 s.push_str(
2455 "# Leave a role list empty to rotate through the roster.\n\
2456 # A non-empty list is also an ordered backup list: seats take entries from the\n\
2457 # front (see [graph] counts) and a failed or out-of-quota seat moves on to the\n\
2458 # next agent to its right, each tried once. Same for judges and reviewers.\n\
2459 # implementers = [\"opus\", \"codex\", \"sonnet\"] # with implementers = 1 below: opus sits, codex then sonnet are spares\n\
2460 [roles]\n\
2461 implementers = []\n\
2462 judges = []\n\
2463 reviewers = []\n\
2464 # conductor = \"opus\" # arranges the queue; unset picks a seat like chatter does\n\
2465 # synthesizer = \"opus\" # blends the advisors into one brief; unset picks a seat like chatter does\n\
2466 # synthesizer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\
2467 # language_judge = \"jev\" # kind = \"command\" wrapper deciding if PR text is English; unset keeps the built-in heuristics\n\
2468 # dupes_judge = \"opus\" # judges duplicate-work claims; unset inherits chatter (string or fallback chain)\n\
2469 # fixer = \"opus\" # applies review findings; unset keeps the winner's own author\n\
2470 # fixer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\n\
2471 [graph]\n\
2472 # Gate GitHub prose; secret redaction is always enabled.\n\
2473 github_text_guard = true\n\
2474 # Language of PR / issue titles, bodies and comments; non-English drops the English-only check (commits stay English).\n\
2475 github_language = \"en\"\n\
2476 implementers = 3\n\
2477 judges = 3\n\
2478 deliberate_rounds = 1\n\
2479 reviewers = 3\n\
2480 review_rounds = 6\n\
2481 # Fix rounds a failing verify.gate gets before the run is blocked (0 = none).\n\
2482 gate_fix_rounds = 1\n\
2483 # Rerun a failed required CI check once before a land fix round (flaky tests).\n\
2484 rerun_flaky_checks = true\n\
2485 # Port the strengths judges named in the losing candidates onto the\n\
2486 # winner before review (best-effort; rolled back on failure or a big diff).\n\
2487 graft_runner_up = true\n\
2488 max_parallel = 4\n\
2489 language = \"en\"\n\
2490 # One CLI conversation per seat: judges keep their own argument\n\
2491 # across deliberation, the fixer keeps its implementation context.\n\
2492 sessions = true\n\
2493 # Reviewer-seat timeout. When timeout_verify is omitted, E2E and\n\
2494 # the final gate inherit this value for compatibility.\n\
2495 timeout_review = 1200\n\
2496 # Optional independent E2E/final-gate timeout; uncomment to keep\n\
2497 # verification independent if timeout_review changes later.\n\
2498 # timeout_verify = 1200\n\
2499 # Longest a seat waits for the shared build cache before it is\n\
2500 # spawned. Never counted against an agent's own timeout; expiry\n\
2501 # holds the run (resumable) instead of failing the agent.\n\
2502 # timeout_resource_wait = 1800\n\n\
2503 # What the chat calls you (persona address and the Chat's turn label).\n\
2504 # [talk]\n\
2505 # operator_name = \"Commander\"\n\n\
2506 # Chat personas (tone only; the web Chat picks one per conversation).\n\
2507 # Built in: magi, rei, misato, ritsuko, shinji, asuka, kaworu. Entries add to\n\
2508 # them, and one with a built-in's id replaces it. `default` is the plain\n\
2509 # voice and cannot be redefined (it may only set `icon`). Declare this in one\n\
2510 # layer only. `icon` is an optional avatar, display only: an absolute or\n\
2511 # ~/ path to a png/jpg/gif/webp, or a data:image/...;base64 URI, up to\n\
2512 # 256 KiB; a missing or bad one falls back to the built-in avatar.\n\
2513 # [[talk.personas]]\n\
2514 # id = \"gendo\"\n\
2515 # name = \"Gendo Ikari\"\n\
2516 # prompt = \"Speak coldly and tersely, hands folded.\"\n\
2517 # icon = \"~/pictures/gendo.png\"\n\n\
2518 [verify]\n\
2519 # Run once per review round in the winner's worktree; failures are\n\
2520 # fed back to the fixer.\n\
2521 e2e = []\n\
2522 # Final gate. Every command must exit 0 before a merge.\n\
2523 gate = []\n\
2524 # Mechanical fixers (formatters) run in the winner's worktree just\n\
2525 # before the gate; whatever they change becomes one commit. A failing\n\
2526 # command only warns - the gate stays the arbiter. Same timeout as the\n\
2527 # gate (timeout_verify). Keep it light and idempotent.\n\
2528 # pre_gate = []\n\n\
2529 # Prepare each worktree magi creates (candidates, judges, advisors,\n\
2530 # reviewers, the operator-fix and review-takeover checkouts), in order,\n\
2531 # before any agent or verify command touches it. `copy` reads from the\n\
2532 # primary checkout and never overwrites; `optional` skips a missing\n\
2533 # source. `run` goes through the shell with the worktree as cwd and\n\
2534 # fails the seat on a non-zero exit or timeout (timeout_secs, default\n\
2535 # the verify timeout). Setup must not edit tracked files, and what it\n\
2536 # leaves untracked is kept out of magi's commits. Declare this in one\n\
2537 # layer only.\n\
2538 # [worktree]\n\
2539 # setup = [\n\
2540 # { copy = \".env.example -> .env\" },\n\
2541 # { copy = \".env.local\", optional = true },\n\
2542 # { run = \"pnpm install --frozen-lockfile\", timeout_secs = 900 },\n\
2543 # ]\n\
2544 # pre_clean = [] # Repeatable cleanup before owned clean -fdx.\n\n\
2545 [merge]\n\
2546 # none | local | pr\n\
2547 mode = \"none\"\n\
2548 # expected (default) | none. Set none only in repository config without CI.\n\
2549 # Ignores all check statuses; reviews and approval still apply.\n\
2550 # ci = \"expected\"\n\
2551 # release_bump = true # Rust (Cargo.toml) repositories only; a no-op elsewhere\n\n\
2552 [update]\n\
2553 # off | notify | install — checked in the background, throttled.\n\
2554 mode = \"notify\"\n\
2555 # interval = \"24h\"\n\n\
2556 # Opt-in: magi web updates and restarts only after runs/chats finish.\n\
2557 # auto_restart = false\n\
2558 # Uses interval above; off / MAGI_NO_AUTOUPDATE disable it.\n\
2559 # Standalone magi serve cannot restart. Busy work waits indefinitely.\n\
2560 # Failed tags are skipped until process restart or a different tag.\n\
2561 # Older binaries reject auto_restart: upgrade before adding the key.\n\n\
2562 [daemon]\n\
2563 # Minutes a release-bump pull request (chore/release-v*) may sit with\n\
2564 # no new commit and no check changing state before `magi serve`\n\
2565 # notices and asks you. A failed check is rerun once on its own;\n\
2566 # still red after that escalates at once. 0 turns the watcher off.\n\
2567 # release_stall_minutes = 60\n\n\
2568 [release]\n\
2569 # actions (default) | local. \"local\" is for repositories whose GitHub\n\
2570 # Actions never run (private, no minutes): the release pull request\n\
2571 # does not wait for CI, you approve the merge in magi, and then\n\
2572 # `magi serve` pushes the vX.Y.Z tag (never over an existing one) and\n\
2573 # runs `commands` from a clean checkout of the merge commit. A\n\
2574 # failure holds the release with a notice; it is never retried blind.\n\
2575 # Needs `magi serve` running and [daemon] release_stall_minutes > 0.\n\
2576 # For ordinary pull requests without CI, also set [merge] ci = \"none\".\n\
2577 # mode = \"actions\"\n\
2578 # Run in order; the first failure stops. They see MAGI_RELEASE_VERSION,\n\
2579 # MAGI_RELEASE_TAG, MAGI_RELEASE_COMMIT and MAGI_RELEASE_PR. Make them\n\
2580 # safe to repeat: a crash mid-command is treated as unfinished.\n\
2581 # commands = [\"cargo build --release\", \"gh release create \\\"$MAGI_RELEASE_TAG\\\" --generate-notes\"]\n\
2582 # timeout_minutes = 30\n\
2583 # Repositories whose Cargo.toml is not at the root (e.g. a Tauri app).\n\
2584 # The first entry is the version of record and must be the file the\n\
2585 # repository's auto-tag.yml reads (kind \"cargo\"); the others are\n\
2586 # rewritten to the same version. Paths are relative to the repository\n\
2587 # root. Cargo.lock beside the first entry follows; package-lock.json\n\
2588 # is not touched.\n\
2589 # version_files = [\n\
2590 # { path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n\
2591 # { path = \"package.json\", kind = \"json\" },\n\
2592 # { path = \"src-tauri/tauri.conf.json\", kind = \"json\" },\n\
2593 # ]\n",
2594 );
2595 s
2596 }
2597}
2598
2599pub fn which(program: &str) -> bool {
2601 find_program(program).is_some()
2602}
2603
2604pub fn find_program(program: &str) -> Option<PathBuf> {
2613 find_program_on(program, &std::env::var_os("PATH")?)
2614}
2615
2616pub fn find_program_on(program: &str, paths: &std::ffi::OsStr) -> Option<PathBuf> {
2619 let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".EXE;.CMD;.BAT".into());
2620 find_program_in(program, paths, cfg!(windows).then_some(pathext.as_str()))
2621}
2622
2623fn find_program_in(
2624 program: &str,
2625 paths: &std::ffi::OsStr,
2626 pathext: Option<&str>,
2627) -> Option<PathBuf> {
2628 let p = Path::new(program);
2629 if p.components().count() > 1 {
2630 return p.is_file().then(|| p.to_path_buf());
2631 }
2632 std::env::split_paths(paths).find_map(|dir| match pathext {
2633 Some(exts) => {
2634 let bare = dir.join(program);
2635 if p.extension().is_some() && bare.is_file() {
2636 return Some(bare);
2637 }
2638 exts.split(';')
2639 .filter(|e| !e.is_empty())
2640 .map(|e| dir.join(format!("{program}{}", e.to_lowercase())))
2641 .find(|c| c.is_file())
2642 }
2643 None => Some(dir.join(program)).filter(|c| c.is_file()),
2644 })
2645}
2646
2647const REPO_MARKER: &str = ".magi-repo";
2649
2650fn git_out(repo: &Path, args: &[&str]) -> Option<String> {
2651 use crate::proc::Quiet as _;
2652 #[cfg(test)]
2653 crate::web::request_cost::git();
2654 let out = std::process::Command::new("git")
2655 .args(args)
2656 .quiet()
2657 .current_dir(repo)
2658 .stdin(std::process::Stdio::null())
2659 .output()
2660 .ok()?;
2661 out.status
2662 .success()
2663 .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
2664}
2665
2666fn is_git_worktree(repo: &Path) -> bool {
2669 git_out(repo, &["rev-parse", "--git-dir"]).is_some()
2670}
2671
2672#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2675pub enum OwnerHold {
2676 LandApproval,
2678 HoldContestedMerge,
2680}
2681
2682impl OwnerHold {
2683 pub const ALL: [Self; 2] = [Self::LandApproval, Self::HoldContestedMerge];
2685
2686 pub fn key(self) -> &'static str {
2688 match self {
2689 Self::LandApproval => "land_approval",
2690 Self::HoldContestedMerge => "hold_contested_merge",
2691 }
2692 }
2693
2694 pub fn base_value(self, graph: &Graph) -> bool {
2696 match self {
2697 Self::LandApproval => graph.land_approval,
2698 Self::HoldContestedMerge => graph.hold_contested_merge,
2699 }
2700 }
2701}
2702
2703pub async fn branch_owner_holds(
2706 repo: &Path,
2707 head: &str,
2708) -> (Vec<(OwnerHold, String)>, Vec<String>) {
2709 let mut holds = Vec::new();
2710 let mut diagnostics = Vec::new();
2711 if let Err(error) =
2714 crate::git::git(repo, &["cat-file", "-e", &format!("{head}^{{commit}}")]).await
2715 {
2716 diagnostics.push(format!("cannot read reviewed commit {head}: {error:#}"));
2717 return (holds, diagnostics);
2718 }
2719 for file in ["magi.toml", ".magi/config.toml"] {
2720 let object = format!("{head}:{file}");
2721 let text = match crate::git::git(repo, &["show", &object]).await {
2722 Ok(text) => text,
2723 Err(error) => {
2724 let error = format!("{error:#}");
2726 if !error.contains("does not exist in")
2727 && !error.contains("exists on disk, but not in")
2728 {
2729 diagnostics.push(format!(
2730 "cannot read reviewed branch {file} at {head}: {error}"
2731 ));
2732 }
2733 continue;
2734 }
2735 };
2736 let value = match toml::from_str::<toml::Value>(&text) {
2737 Ok(value) => value,
2738 Err(error) => {
2739 diagnostics.push(format!(
2740 "cannot parse reviewed branch {file} at {head}: {error}"
2741 ));
2742 continue;
2743 }
2744 };
2745 if value.get("include").is_some() || text.contains("{{") || text.contains("{%") {
2746 diagnostics.push(format!("reviewed branch {file} at {head}: only literal owner holds are read; includes and templates are ignored"));
2747 }
2748 for hold in OwnerHold::ALL {
2749 if value
2750 .get("graph")
2751 .and_then(|g| g.get(hold.key()))
2752 .and_then(toml::Value::as_bool)
2753 == Some(true)
2754 {
2755 holds.push((hold, file.to_owned()));
2756 }
2757 }
2758 }
2759 (holds, diagnostics)
2760}
2761
2762#[derive(Deserialize, Default)]
2763struct ProbeMerge {
2764 base: Option<String>,
2765 remote: Option<String>,
2766}
2767
2768#[derive(Deserialize, Default)]
2769struct Probe {
2770 merge: Option<ProbeMerge>,
2771}
2772
2773fn probe_merge(path: &Path, repo: &Path) -> Option<ProbeMerge> {
2779 if !path.is_file() {
2780 return None;
2781 }
2782 let paths = [path.to_path_buf()];
2783 let mut engine = teravars::Engine::default();
2784 let mut ctx = Config::render_ctx(&paths);
2785 ctx.insert("repo", &repo.to_string_lossy());
2788 ctx.insert(
2789 "repo_name",
2790 &repo.file_name().unwrap_or_default().to_string_lossy(),
2791 );
2792 if let Ok(merged) = teravars::load_merged(&paths, &mut engine, &ctx)
2793 && let Ok(probe) = toml::Value::Table(merged.config).try_into::<Probe>()
2794 {
2795 return probe.merge;
2796 }
2797 let text = std::fs::read_to_string(path).ok()?;
2798 toml::from_str::<Probe>(&text).ok()?.merge
2799}
2800
2801fn probe_remote_base(repo: &Path) -> (String, Option<String>) {
2803 let mut remote = None;
2804 let mut base = None;
2805 let mut sources: Vec<PathBuf> = Config::machine_layer().into_iter().collect();
2806 sources.push(repo.join("magi.toml"));
2807 sources.push(repo.join(".magi").join("config.toml"));
2808 for path in sources {
2809 if let Some(m) = probe_merge(&path, repo) {
2810 remote = remote.or(m.remote.filter(|s| !s.trim().is_empty()));
2811 base = base.or(m.base.filter(|s| !s.trim().is_empty()));
2812 }
2813 }
2814 (remote.unwrap_or_else(|| "origin".to_owned()), base)
2815}
2816
2817fn resolve_remote_base(repo: &Path) -> Result<(String, String)> {
2819 let (remote, base) = probe_remote_base(repo);
2820 let base = match base {
2821 Some(b) => b,
2822 None => {
2823 let head = format!("refs/remotes/{remote}/HEAD");
2824 git_out(repo, &["symbolic-ref", "--quiet", &head])
2825 .and_then(|s| crate::git::remote_head_branch(&remote, &s))
2826 .with_context(|| {
2827 format!(
2828 "cannot tell which branch of `{remote}` holds magi.toml: \
2829 set [merge] base, or run `git remote set-head {remote} -a`"
2830 )
2831 })?
2832 }
2833 };
2834 Ok((remote, base))
2835}
2836
2837fn fnv_hex(text: &str) -> String {
2838 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
2839 for b in text.bytes() {
2840 hash ^= u64::from(b);
2841 hash = hash.wrapping_mul(0x0100_0000_01b3);
2842 }
2843 format!("{hash:016x}")
2844}
2845
2846fn declares_include(text: &str) -> bool {
2852 match toml::from_str::<toml::Table>(text) {
2853 Ok(table) => {
2854 table.contains_key("include")
2855 || table
2856 .get("teravars")
2857 .and_then(toml::Value::as_table)
2858 .is_some_and(|t| t.contains_key("include"))
2859 }
2860 Err(_) => text.contains("include"),
2861 }
2862}
2863
2864fn extract_tree(repo: &Path, sha: &str, dest: &Path) -> Result<()> {
2867 use crate::proc::Quiet as _;
2868 #[cfg(test)]
2869 crate::web::request_cost::git();
2870 let mut archive = std::process::Command::new("git")
2871 .args(["archive", "--format=tar", sha])
2872 .quiet()
2873 .current_dir(repo)
2874 .stdin(std::process::Stdio::null())
2875 .stdout(std::process::Stdio::piped())
2876 .stderr(std::process::Stdio::null())
2877 .spawn()
2878 .context("running git archive")?;
2879 let tar = std::process::Command::new("tar")
2880 .arg("-x")
2881 .arg("-C")
2882 .arg(dest)
2883 .quiet()
2884 .stdin(archive.stdout.take().context("git archive has no stdout")?)
2885 .output()
2886 .context("running tar")?;
2887 let status = archive.wait().context("waiting for git archive")?;
2888 if !status.success() || !tar.status.success() {
2889 bail!(
2890 "cannot unpack {sha} for the config's includes: {}",
2891 String::from_utf8_lossy(&tar.stderr).trim()
2892 );
2893 }
2894 Ok(())
2895}
2896
2897fn remote_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2900 let (remote, base) = resolve_remote_base(repo)?;
2901 let tracking = format!("refs/remotes/{remote}/{base}");
2902 let spec = format!("{tracking}^{{commit}}");
2903 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
2904 .map(|s| s.trim().to_owned())
2905 .filter(|s| !s.is_empty())
2906 .with_context(|| {
2907 format!(
2908 "`{remote}/{base}` does not exist in this checkout; fetch it \
2909 (`git fetch {remote} {base}`) or set [merge] base/remote. magi will not read \
2910 a possibly stale local magi.toml instead"
2911 )
2912 })?;
2913 let key = format!("{sha}-{}", fnv_hex(&repo.to_string_lossy()));
2914 let rels = [".magi/config.toml", "magi.toml"];
2915 let mut texts: Vec<(&str, String)> = Vec::new();
2916 for rel in rels {
2917 let object = format!("{sha}:{rel}");
2918 if git_out(repo, &["cat-file", "-e", &object]).is_none() {
2919 continue;
2920 }
2921 let Some(text) = git_out(repo, &["show", &object]) else {
2922 bail!("cannot read {rel} from {remote}/{base} ({sha})");
2923 };
2924 texts.push((rel, text));
2925 }
2926 let wants_tree = texts.iter().any(|(_, t)| declares_include(t));
2927 let build = |root: &Path| -> Result<PathBuf> {
2931 let final_dir = root.join(&key);
2932 if !final_dir.is_dir() {
2933 std::fs::create_dir_all(root)?;
2934 let tmp = root.join(format!(
2935 "{key}.tmp-{}-{}",
2936 std::process::id(),
2937 std::time::SystemTime::now()
2938 .duration_since(std::time::UNIX_EPOCH)
2939 .map(|d| d.as_nanos())
2940 .unwrap_or_default()
2941 ));
2942 let filled = (|| -> Result<()> {
2943 std::fs::create_dir_all(&tmp)?;
2944 if wants_tree {
2945 extract_tree(repo, &sha, &tmp)?;
2946 }
2947 for (rel, text) in &texts {
2948 let file = tmp.join(rel);
2949 let parent = file.parent().unwrap_or(&tmp);
2950 std::fs::create_dir_all(parent)?;
2951 std::fs::write(&file, text)?;
2952 std::fs::write(parent.join(REPO_MARKER), repo.to_string_lossy().as_bytes())?;
2953 }
2954 Ok(())
2955 })();
2956 if let Err(e) = filled {
2957 let _ = std::fs::remove_dir_all(&tmp);
2958 return Err(e);
2959 }
2960 if std::fs::rename(&tmp, &final_dir).is_err() {
2961 let _ = std::fs::remove_dir_all(&tmp);
2963 if !final_dir.is_dir() {
2964 bail!("cannot place {}", final_dir.display());
2965 }
2966 }
2967 }
2968 Ok(final_dir)
2969 };
2970 let common = git_out(
2971 repo,
2972 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
2973 )
2974 .map(|s| PathBuf::from(s.trim()).join("magi").join("config"));
2975 let dir = match common.map(|c| build(&c)) {
2976 Some(Ok(d)) => d,
2977 _ => build(&std::env::temp_dir().join("magi-config"))
2978 .with_context(|| format!("extracting config from {remote}/{base}"))?,
2979 };
2980 Ok(texts.iter().map(|(rel, _)| dir.join(rel)).collect())
2981}
2982
2983#[cfg(test)]
2984mod tests {
2985 #[test]
2986 fn run_records_with_the_retired_editing_network_key_still_load() {
2987 for value in ["enabled", "restricted"] {
2989 let mut graph = serde_json::to_value(Graph::default()).unwrap();
2990 graph["editing_network"] = serde_json::json!(value);
2991 let back: Graph = serde_json::from_value(graph).unwrap();
2992 assert!(
2993 serde_json::to_value(&back)
2994 .unwrap()
2995 .get("editing_network")
2996 .is_none()
2997 );
2998 let from_toml: Graph = toml::from_str(&format!("editing_network = {value:?}")).unwrap();
2999 assert!(
3000 !toml::to_string(&from_toml)
3001 .unwrap()
3002 .contains("editing_network")
3003 );
3004 }
3005 }
3006
3007 #[test]
3008 fn coordination_defaults_off_and_validates_rendered_layer_values() {
3009 let dir = tempfile::tempdir().unwrap();
3010 let machine = dir.path().join("machine.toml");
3011 let repo = dir.path().join("repo.toml");
3012 std::fs::write(&machine, "").unwrap();
3013 assert!(Config::default().coordination.is_none());
3014 assert!(Config::load(&machine).unwrap().coordination.is_none());
3015 std::fs::write(
3016 &machine,
3017 r#"
3018[vars]
3019contract = "updater.contract"
3020[coordination]
3021contract_file = "{{ vars.contract }}"
3022contract_token = "protocol-v1"
3023lock_file = "updater.lock"
3024"#,
3025 )
3026 .unwrap();
3027 let cfg = Config::load(&machine).unwrap();
3028 let policy = cfg.coordination.unwrap();
3029 assert_eq!(policy.contract_file, "updater.contract");
3030 assert_eq!(policy.contract_token, "protocol-v1");
3031 assert_eq!(policy.lock_file, "updater.lock");
3032 std::fs::write(&repo, "[coordination]\nlock_file = 'repository.lock'\n").unwrap();
3033 let cfg = Config::load_layers(&[machine.clone(), repo.clone()]).unwrap();
3034 let policy = cfg.coordination.unwrap();
3035 assert_eq!(policy.contract_file, "updater.contract");
3036 assert_eq!(policy.lock_file, "repository.lock");
3037 std::fs::write(
3038 &repo,
3039 r#"
3040[vars]
3041bad = "../escape"
3042[coordination]
3043lock_file = "{{ vars.bad }}"
3044"#,
3045 )
3046 .unwrap();
3047 let error = Config::load_layers(&[machine, repo]).unwrap_err();
3048 assert!(format!("{error:#}").contains("coordination.lock_file"));
3049 }
3050
3051 #[test]
3052 fn coordination_rejects_invalid_names_tokens_and_incomplete_sections() {
3053 let dir = tempfile::tempdir().unwrap();
3054 let path = dir.path().join("config.toml");
3055 let valid = toml::toml! {
3056 [coordination]
3057 contract_file = "updater.contract"
3058 contract_token = "protocol-v1"
3059 lock_file = "updater.lock"
3060 };
3061 for key in ["contract_file", "lock_file"] {
3062 for bad in [
3063 "",
3064 " ",
3065 " file",
3066 "file ",
3067 "\tfile",
3068 "file\t",
3069 ".",
3070 "..",
3071 "file..name",
3072 "../escape",
3073 "a/b",
3074 "a\\b",
3075 "/absolute",
3076 "C:drive",
3077 "C:\\absolute",
3078 "nul\0name",
3079 ] {
3080 let mut table = valid.clone();
3081 table["coordination"][key] = bad.into();
3082 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3083 let error = Config::load(&path).unwrap_err();
3084 assert!(
3085 format!("{error:#}").contains(&format!("coordination.{key}")),
3086 "{bad:?}: {error:#}"
3087 );
3088 }
3089 }
3090 for bad in ["", " ", " token", "token ", "two\nlines", "two\rlines"] {
3091 let mut table = valid.clone();
3092 table["coordination"]["contract_token"] = bad.into();
3093 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3094 let error = Config::load(&path).unwrap_err();
3095 assert!(
3096 format!("{error:#}").contains("coordination.contract_token"),
3097 "{error:#}"
3098 );
3099 }
3100 for key in ["contract_file", "contract_token", "lock_file"] {
3101 let mut table = valid.clone();
3102 table["coordination"].as_table_mut().unwrap().remove(key);
3103 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3104 let error = Config::load(&path).unwrap_err();
3105 assert!(
3106 format!("{error:#}").contains(&format!("coordination.{key}")),
3107 "{error:#}"
3108 );
3109 }
3110 let mut table = valid;
3111 table["coordination"]
3112 .as_table_mut()
3113 .unwrap()
3114 .insert("typo".into(), "value".into());
3115 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3116 assert!(format!("{:#}", Config::load(&path).unwrap_err()).contains("typo"));
3117 }
3118
3119 #[test]
3120 fn context_window_prefers_exact_then_longest_prefix_and_user_over_builtin() {
3121 let mut cfg = Config::default();
3122 assert_eq!(
3123 cfg.context_window("claude-sonnet-4-5-20250929"),
3124 Some(200_000)
3125 );
3126 assert_eq!(cfg.context_window("gpt-4.1-mini"), Some(1_000_000));
3127 assert_eq!(cfg.context_window("mystery-model"), None);
3128 cfg.context_windows
3129 .insert("claude-sonnet-4-5".into(), 1_000_000);
3130 cfg.context_windows.insert("claude-sonnet-4".into(), 5);
3131 cfg.context_windows.insert("mystery".into(), 32_768);
3132 assert_eq!(
3134 cfg.context_window("claude-sonnet-4-5-20250929"),
3135 Some(1_000_000)
3136 );
3137 cfg.context_windows
3139 .insert("claude-sonnet-4-5-20250929".into(), 7);
3140 assert_eq!(cfg.context_window("claude-sonnet-4-5-20250929"), Some(7));
3141 assert_eq!(cfg.context_window("mystery-model"), Some(32_768));
3142 }
3143
3144 use super::*;
3145
3146 #[test]
3149 fn windows_lookup_picks_the_cmd_shim_over_the_extensionless_script() {
3150 let dir = tempfile::tempdir().unwrap();
3151 std::fs::write(dir.path().join("codex"), "#!/bin/sh\n").unwrap();
3152 std::fs::write(dir.path().join("codex.cmd"), "@echo off\n").unwrap();
3153 let paths = dir.path().as_os_str();
3154 assert_eq!(
3155 find_program_in("codex", paths, Some(".EXE;.CMD")),
3156 Some(dir.path().join("codex.cmd"))
3157 );
3158 assert_eq!(
3159 find_program_in("codex", paths, None),
3160 Some(dir.path().join("codex"))
3161 );
3162 assert_eq!(find_program_in("claude", paths, Some(".EXE;.CMD")), None);
3163 }
3164
3165 fn spec(id: &str) -> AgentSpec {
3166 AgentSpec {
3167 id: id.to_owned(),
3168 kind: AgentKind::Command,
3169 model: None,
3170 command: vec!["true".to_owned()],
3171 extra_args: Vec::new(),
3172 env: BTreeMap::new(),
3173 prompt_delivery: None,
3174 max_turn_secs: None,
3175 }
3176 }
3177
3178 #[test]
3179 fn merge_ci_defaults_expected_and_requires_an_explicit_valid_opt_out() {
3180 let default: Merge = toml::from_str("").unwrap();
3181 assert_eq!(default.ci, MergeCi::Expected);
3182 let config = layered("", "[merge]\nci = \"none\"\n").unwrap();
3183 assert_eq!(
3184 config.merge.ci.expectation(),
3185 crate::land::CiExpectation::Absent
3186 );
3187 assert!(toml::from_str::<Merge>("ci = \"typo\"").is_err());
3188 assert!(Config::starter_toml().contains("# ci = \"expected\""));
3189 }
3190
3191 #[test]
3192 fn github_text_guard_defaults_on_and_can_be_disabled() {
3193 let default: Graph = toml::from_str("").unwrap();
3194 assert!(default.github_text_guard);
3195 let disabled: Graph = toml::from_str("github_text_guard = false").unwrap();
3196 assert!(!disabled.github_text_guard);
3197 let config = layered("", "[graph]\ngithub_text_guard = false\n").unwrap();
3198 assert!(!config.graph.github_text_guard);
3199 assert!(Config::starter_toml().contains("github_text_guard = true"));
3200 }
3201
3202 #[test]
3203 fn rerun_flaky_checks_defaults_on_and_is_in_the_starter() {
3204 assert!(Graph::default().rerun_flaky_checks);
3205 let off: Graph = toml::from_str("rerun_flaky_checks = false").unwrap();
3206 assert!(!off.rerun_flaky_checks);
3207 assert!(Config::starter_toml().contains("rerun_flaky_checks = true"));
3208 }
3209
3210 #[test]
3211 fn timeout_verify_omitted_from_old_toml_inherits_timeout_review() {
3212 let g: Graph = toml::from_str("timeout_review = 3600").expect("parse");
3217 assert_eq!(g.timeout_verify, None);
3218 assert_eq!(g.verify_timeout(), 3600);
3219 }
3220
3221 #[test]
3222 fn shrinking_timeout_review_does_not_shrink_timeout_verify() {
3223 let g: Graph = toml::from_str("timeout_review = 45").expect("parse");
3228 assert_eq!(g.timeout_review, 45);
3229 assert_eq!(
3230 g.verify_timeout(),
3231 45,
3232 "an omitted legacy value follows review"
3233 );
3234 let explicit: Graph = toml::from_str("timeout_review = 45\ntimeout_verify = 1200")
3235 .expect("parse explicit override");
3236 assert_eq!(explicit.verify_timeout(), 1200);
3237 }
3238
3239 #[test]
3240 fn graph_implementers_new_key_loads_and_old_key_is_an_alias() {
3241 let g: Graph = toml::from_str("implementers = 4\n").unwrap();
3242 assert_eq!(g.implementers, 4);
3243 let g: Graph = toml::from_str("candidates = 5\n").unwrap();
3244 assert_eq!(g.implementers, 5);
3245 }
3246
3247 fn layered(lower: &str, upper: &str) -> Result<Config> {
3248 let dir = tempfile::tempdir().unwrap();
3249 let a = dir.path().join("a.toml");
3250 let b = dir.path().join("b.toml");
3251 std::fs::write(&a, lower).unwrap();
3252 std::fs::write(&b, upper).unwrap();
3253 Config::load_layers(&[a, b])
3254 }
3255
3256 #[test]
3257 fn graph_implementers_higher_layer_wins_across_spellings() {
3258 let c = layered("[graph]\ncandidates = 2\n", "[graph]\nimplementers = 5\n").unwrap();
3259 assert_eq!(c.graph.implementers, 5);
3260 let c = layered("[graph]\nimplementers = 2\n", "[graph]\ncandidates = 5\n").unwrap();
3261 assert_eq!(c.graph.implementers, 5);
3262 let c = layered("[graph]\ncandidates = 2\n", "[graph]\njudges = 3\n").unwrap();
3263 assert_eq!(c.graph.implementers, 2);
3264 }
3265
3266 #[test]
3267 fn graph_implementers_both_keys_in_one_layer_is_refused() {
3268 let err = layered("", "[graph]\ncandidates = 2\nimplementers = 3\n")
3269 .unwrap_err()
3270 .to_string();
3271 assert!(
3272 err.contains("candidates") && err.contains("implementers"),
3273 "{err}"
3274 );
3275 assert!(err.contains("b.toml"), "{err}");
3276 }
3277
3278 #[test]
3279 fn a_toml_layer_written_before_these_fields_existed_still_parses() {
3280 let g: Graph =
3284 toml::from_str("candidates = 1\nreviewers = 3\nreview_rounds = 6\nmax_parallel = 4\n")
3285 .expect("an old-shaped [graph] table must still parse");
3286 assert_eq!(g.verify_timeout(), Graph::default().timeout_review);
3287 assert!(
3288 !g.e2e_every_round,
3289 "off by default, same as before this field existed"
3290 );
3291 }
3292
3293 #[test]
3294 fn empty_roles_rotate_judges_off_their_own_candidate() {
3295 let cfg = Config {
3298 agents: vec![spec("a"), spec("b"), spec("c")],
3299 graph: Graph {
3300 implementers: 3,
3301 ..Graph::default()
3302 },
3303 ..Config::default()
3304 };
3305 let roles = cfg.resolve_roles().unwrap();
3306 let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
3307 let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
3308 assert_eq!(impls, ["a", "b", "c"]);
3309 assert_eq!(judges, ["b", "c", "a"]);
3310 for (i, j) in judges.iter().enumerate() {
3311 assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
3312 }
3313 }
3314
3315 #[test]
3316 fn single_agent_roster_fills_every_seat() {
3317 let cfg = Config {
3318 agents: vec![spec("solo")],
3319 graph: Graph {
3320 implementers: 3,
3321 ..Graph::default()
3322 },
3323 ..Config::default()
3324 };
3325 let roles = cfg.resolve_roles().unwrap();
3326 assert_eq!(roles.implementers.len(), 3);
3327 assert!(roles.judges.iter().all(|a| a.id == "solo"));
3328 }
3329
3330 #[test]
3331 fn implementer_roster_is_the_whole_agent_list_untruncated_when_unset() {
3332 let cfg = Config {
3337 agents: vec![spec("a"), spec("b"), spec("c")],
3338 graph: Graph {
3339 implementers: 1,
3340 ..Graph::default()
3341 },
3342 ..Config::default()
3343 };
3344 let roles = cfg.resolve_roles().unwrap();
3345 assert_eq!(roles.implementers.len(), 1);
3346 let roster: Vec<&str> = roles
3347 .implementer_roster
3348 .iter()
3349 .map(|a| a.id.as_str())
3350 .collect();
3351 assert_eq!(roster, ["a", "b", "c"]);
3352 }
3353
3354 #[test]
3355 fn implementer_roster_follows_explicit_ids_in_the_order_named() {
3356 let cfg = Config {
3357 agents: vec![spec("a"), spec("b"), spec("c")],
3358 roles: Roles {
3359 implementers: vec!["c".to_owned(), "a".to_owned()],
3360 ..Roles::default()
3361 },
3362 graph: Graph {
3363 implementers: 1,
3364 ..Graph::default()
3365 },
3366 ..Config::default()
3367 };
3368 let roles = cfg.resolve_roles().unwrap();
3369 assert_eq!(roles.implementers.len(), 1);
3371 assert_eq!(roles.implementers[0].id, "c");
3372 let roster: Vec<&str> = roles
3373 .implementer_roster
3374 .iter()
3375 .map(|a| a.id.as_str())
3376 .collect();
3377 assert_eq!(roster, ["c", "a"]);
3378 }
3379
3380 #[test]
3381 fn explicit_roles_win() {
3382 let cfg = Config {
3383 agents: vec![spec("a"), spec("b")],
3384 roles: Roles {
3385 implementers: vec!["b".to_owned()],
3386 judges: vec!["a".to_owned()],
3387 reviewers: Vec::new(),
3388 fixer: Some("a".into()),
3389 ..Roles::default()
3390 },
3391 ..Config::default()
3392 };
3393 let roles = cfg.resolve_roles().unwrap();
3394 assert!(roles.implementers.iter().all(|a| a.id == "b"));
3395 assert!(roles.judges.iter().all(|a| a.id == "a"));
3396 let fixer = roles.fixer.unwrap();
3397 assert_eq!(fixer.len(), 1);
3398 assert_eq!(fixer[0].id, "a");
3399 assert_eq!(roles.conductor.id, "a");
3400 }
3401
3402 #[test]
3403 fn fixer_takes_a_string_or_an_ordered_chain() {
3404 let one: Roles = toml::from_str("fixer = \"a\"").unwrap();
3405 assert_eq!(one.fixer.as_ref().unwrap().ids(), ["a"]);
3406 let chain: Roles = toml::from_str("fixer = [\"b\", \"a\"]").unwrap();
3407 assert_eq!(chain.fixer.as_ref().unwrap().ids(), ["b", "a"]);
3408
3409 let resolve = |fixer: Option<AgentChoice>| {
3410 Config {
3411 agents: vec![spec("a"), spec("b"), spec("c")],
3412 roles: Roles {
3413 fixer,
3414 ..Roles::default()
3415 },
3416 ..Config::default()
3417 }
3418 .resolve_roles()
3419 };
3420 let ids = |r: &ResolvedRoles| -> Vec<String> {
3421 r.fixer
3422 .as_ref()
3423 .unwrap()
3424 .iter()
3425 .map(|s| s.id.clone())
3426 .collect()
3427 };
3428 assert_eq!(ids(&resolve(Some("c".into())).unwrap()), ["c"]);
3430 assert!(resolve(None).unwrap().fixer.is_none());
3431 let chain = AgentChoice::Chain(vec!["b".into(), "zzz".into(), "a".into(), "b".into()]);
3433 assert_eq!(ids(&resolve(Some(chain)).unwrap()), ["b", "a"]);
3434 let err = resolve(Some(AgentChoice::Chain(vec!["zzz".into()]))).unwrap_err();
3436 assert!(format!("{err:#}").contains("fixer"), "{err:#}");
3437 }
3438
3439 #[test]
3440 fn unknown_agent_id_is_an_error() {
3441 let cfg = Config {
3442 agents: vec![spec("a")],
3443 roles: Roles {
3444 judges: vec!["nope".to_owned()],
3445 ..Roles::default()
3446 },
3447 ..Config::default()
3448 };
3449 assert!(cfg.resolve_roles().is_err());
3450 }
3451
3452 #[test]
3453 fn conductor_role_is_resolved_validated_and_has_a_fallback() {
3454 let mut cfg = Config {
3455 agents: vec![spec("a"), spec("b")],
3456 ..Config::default()
3457 };
3458 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "a");
3459
3460 cfg.roles.conductor = Some("b".into());
3461 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "b");
3462
3463 cfg.roles.conductor = Some("missing".into());
3464 assert!(cfg.resolve_roles().is_err());
3465 }
3466
3467 #[test]
3468 fn a_standalone_role_takes_a_string_or_an_array_and_round_trips() {
3469 let one: Roles = toml::from_str("synthesizer = \"opus\"").unwrap();
3470 assert_eq!(one.synthesizer, Some(AgentChoice::One("opus".to_owned())));
3471 assert_eq!(primary(one.synthesizer.as_ref()), Some("opus"));
3472
3473 let chain: Roles = toml::from_str("chatter = [\"opus\", \"codex\"]").unwrap();
3474 assert_eq!(chain.chatter.as_ref().unwrap().ids(), ["opus", "codex"]);
3475 assert_eq!(primary(chain.chatter.as_ref()), Some("opus"));
3476
3477 for roles in [one, chain] {
3478 let text = toml::to_string(&roles).unwrap();
3479 let back: Roles = toml::from_str(&text).unwrap();
3480 assert_eq!(back.synthesizer, roles.synthesizer);
3481 assert_eq!(back.chatter, roles.chatter);
3482 }
3483 let text = toml::to_string(&Roles {
3484 conductor: Some("x".into()),
3485 ..Roles::default()
3486 })
3487 .unwrap();
3488 assert!(
3489 text.contains("conductor = \"x\""),
3490 "string stays a string: {text}"
3491 );
3492 assert!(toml::from_str::<Roles>("synthesizer = 3").is_err());
3493 }
3494
3495 #[test]
3496 fn dupes_judge_role_accepts_strings_and_chains_and_round_trips() {
3497 for (text, ids) in [
3498 (r#"dupes_judge = "dedicated""#, vec!["dedicated"]),
3499 (
3500 r#"dupes_judge = ["first", "second"]"#,
3501 vec!["first", "second"],
3502 ),
3503 ("dupes_judge = []", vec![]),
3504 ] {
3505 let roles: Roles = toml::from_str(text).unwrap();
3506 assert_eq!(roles.dupes_judge.as_ref().unwrap().ids(), ids);
3507 let serialized = toml::to_string(&roles).unwrap();
3508 let back: Roles = toml::from_str(&serialized).unwrap();
3509 assert_eq!(back.dupes_judge, roles.dupes_judge);
3510 assert!(serialized.contains(text));
3511 }
3512 assert!(toml::from_str::<Roles>("dupes_judge = 3").is_err());
3513 assert!(Roles::default().dupes_judge.is_none());
3514 assert!(Config::starter_toml().contains("# dupes_judge ="));
3515
3516 let mut cfg = Config {
3518 agents: vec![spec("a")],
3519 ..Config::default()
3520 };
3521 cfg.roles.dupes_judge = Some("missing".into());
3522 assert!(cfg.resolve_roles().is_ok());
3523 }
3524
3525 #[test]
3526 fn an_empty_choice_counts_as_unset() {
3527 assert!(AgentChoice::Chain(Vec::new()).ids().is_empty());
3528 assert!(AgentChoice::One(" ".to_owned()).ids().is_empty());
3529 assert_eq!(primary(Some(&AgentChoice::Chain(vec![]))), None);
3530 }
3531
3532 #[test]
3533 fn synthesizer_role_is_a_lazy_lookup_with_the_same_fallback_as_chatter() {
3534 let mut cfg = Config {
3540 agents: vec![spec("a"), spec("b")],
3541 ..Config::default()
3542 };
3543 let want = primary(cfg.roles.synthesizer.as_ref());
3544 assert_eq!(
3545 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
3546 .unwrap()
3547 .id,
3548 "a",
3549 "unset falls back to agent::pick's own default order"
3550 );
3551
3552 cfg.roles.synthesizer = Some("b".into());
3553 let want = primary(cfg.roles.synthesizer.as_ref());
3554 assert_eq!(
3555 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
3556 .unwrap()
3557 .id,
3558 "b",
3559 "the named agent wins over the default order"
3560 );
3561 }
3562
3563 #[test]
3564 fn empty_roster_is_an_error() {
3565 assert!(Config::default().resolve_roles().is_err());
3566 }
3567
3568 #[test]
3569 fn advise_defaults_to_on_with_three_proposals() {
3570 let g = Graph::default();
3571 assert!(g.advise);
3572 assert!(g.graft_runner_up, "graft is on by default");
3573 assert_eq!(g.advisors, 3);
3574 }
3575
3576 #[test]
3577 fn unset_advisors_falls_back_to_the_judge_roster() {
3578 let cfg = Config {
3579 agents: vec![spec("a"), spec("b")],
3580 roles: Roles {
3581 judges: vec!["b".to_owned()],
3582 ..Roles::default()
3583 },
3584 graph: Graph {
3585 advisors: 2,
3586 ..Graph::default()
3587 },
3588 ..Config::default()
3589 };
3590 let advisors = cfg.advisors().expect("advisors resolve");
3591 assert_eq!(advisors.len(), 2);
3592 assert!(
3593 advisors.iter().all(|a| a.id == "b"),
3594 "an unset [roles] advisors must fall back to [roles] judges: {advisors:?}"
3595 );
3596 }
3597
3598 #[test]
3599 fn an_explicit_advisor_roster_wins_over_the_judge_fallback() {
3600 let cfg = Config {
3601 agents: vec![spec("a"), spec("b")],
3602 roles: Roles {
3603 judges: vec!["b".to_owned()],
3604 advisors: vec!["a".to_owned()],
3605 ..Roles::default()
3606 },
3607 graph: Graph {
3608 advisors: 2,
3609 ..Graph::default()
3610 },
3611 ..Config::default()
3612 };
3613 let advisors = cfg.advisors().expect("advisors resolve");
3614 assert!(advisors.iter().all(|a| a.id == "a"));
3615 }
3616
3617 #[test]
3623 fn an_unconfigured_advisor_and_judge_roster_resolve_to_the_same_agents() {
3624 let cfg = Config {
3625 agents: vec![spec("a"), spec("b"), spec("c")],
3626 graph: Graph {
3627 advisors: 3,
3628 judges: 3,
3629 ..Graph::default()
3630 },
3631 ..Config::default()
3632 };
3633 let advisors = cfg.advisors().expect("advisors resolve");
3634 let judges = cfg.resolve_roles().expect("roles resolve").judges;
3635 let advisor_ids: Vec<&str> = advisors.iter().map(|a| a.id.as_str()).collect();
3636 let judge_ids: Vec<&str> = judges.iter().map(|a| a.id.as_str()).collect();
3637 assert_eq!(
3638 advisor_ids, judge_ids,
3639 "an unconfigured advisor roster must be the same seats an unconfigured judge panel gets"
3640 );
3641 }
3642
3643 #[test]
3644 fn an_unresolvable_advisor_seat_is_an_error_naming_the_id() {
3645 let cfg = Config {
3646 agents: vec![spec("a")],
3647 roles: Roles {
3648 advisors: vec!["nope".to_owned()],
3649 ..Roles::default()
3650 },
3651 graph: Graph {
3652 advisors: 1,
3653 ..Graph::default()
3654 },
3655 ..Config::default()
3656 };
3657 let err = cfg.advisors().expect_err("`nope` is not in the roster");
3658 assert!(format!("{err:#}").contains("nope"));
3659 }
3660
3661 #[test]
3662 fn repos_default_to_no_roots_and_a_day_of_trust() {
3663 assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
3664 assert_eq!(Config::default().repos.scan_ttl, 86_400);
3665 assert_eq!(Config::default().repos.fetch_interval, 600);
3666 assert!(!Config::default().repos.auto_clone);
3667 assert!(Config::default().repos.clone_command.is_none());
3668 }
3669
3670 #[test]
3671 fn a_config_file_with_no_repos_table_still_loads() {
3672 let dir = tempfile::tempdir().unwrap();
3673 let path = dir.path().join("magi.toml");
3674 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
3675 let cfg = Config::load(&path).expect("must load without [repos]");
3676 assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
3677 assert_eq!(cfg.repos.scan_ttl, 86_400);
3678 }
3679
3680 #[test]
3695 fn a_test_build_does_not_read_the_operators_machine_config() {
3696 let repo = tempfile::tempdir().unwrap();
3697 std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
3698
3699 let layers = Config::layers(repo.path());
3700 assert_eq!(
3701 layers,
3702 vec![repo.path().join("magi.toml")],
3703 "only the fixture's own file may be a layer"
3704 );
3705 if let Some(real) = dirs::config_dir() {
3706 let machine = real.join("magi").join("config.toml");
3707 assert!(
3708 !layers.contains(&machine),
3709 "the operator's {} must not be a layer in a test build",
3710 machine.display()
3711 );
3712 }
3713 }
3714
3715 #[test]
3716 fn auto_upgrade_config_defaults_and_opt_in() {
3717 let default: Update = toml::from_str("").unwrap();
3718 assert!(!default.auto_restart);
3719 assert_eq!(default.mode, UpdateMode::Notify);
3720 let enabled: Update = toml::from_str("auto_restart = true\ninterval = \"2h\"\n").unwrap();
3721 assert!(enabled.auto_restart);
3722 assert_eq!(enabled.interval.as_deref(), Some("2h"));
3723 assert!(toml::from_str::<Update>("auto_restart = \"yes\"").is_err());
3724 }
3725
3726 #[test]
3727 fn starter_toml_loads_through_teravars() {
3728 let dir = tempfile::tempdir().unwrap();
3729 let path = dir.path().join("magi.toml");
3730 std::fs::write(&path, Config::starter_toml()).unwrap();
3731 let parsed = Config::load(&path).expect("starter config must load");
3732 assert_eq!(parsed.graph.implementers, 3);
3733 assert_eq!(parsed.merge.mode, MergeMode::None);
3734 assert_eq!(parsed.merge.style, MergeStyle::Merge);
3735 assert!(parsed.graph.sessions);
3736 assert!(parsed.graph.github_text_guard);
3737 assert_eq!(parsed.graph.timeout_review, 1200);
3738 assert_eq!(parsed.graph.verify_timeout(), 1200);
3739 assert_eq!(parsed.update.mode, UpdateMode::Notify);
3740 }
3741
3742 #[test]
3743 fn release_defaults_to_actions_and_the_starter_documents_it() {
3744 let dir = tempfile::tempdir().unwrap();
3745 let path = dir.path().join("magi.toml");
3746 std::fs::write(&path, Config::starter_toml()).unwrap();
3747 let r = Config::load(&path).unwrap().release;
3748 assert_eq!(r.mode, ReleaseMode::Actions);
3749 assert!(!r.is_local());
3750 assert!(r.commands.is_empty());
3751 assert_eq!(r.timeout_minutes, 30);
3752 assert!(Config::starter_toml().contains("# mode = \"actions\""));
3753 }
3754
3755 #[test]
3756 fn release_local_parses_and_unknown_keys_are_refused() {
3757 let dir = tempfile::tempdir().unwrap();
3758 let path = dir.path().join("magi.toml");
3759 std::fs::write(
3760 &path,
3761 "[release]\nmode = \"local\"\ncommands = [\"true\", \"echo $MAGI_RELEASE_TAG\"]\ntimeout_minutes = 5\n",
3762 )
3763 .unwrap();
3764 let r = Config::load(&path).unwrap().release;
3765 assert!(r.is_local());
3766 assert_eq!(r.commands.len(), 2);
3767 assert_eq!(r.timeout_minutes, 5);
3768 std::fs::write(&path, "[release]\nmode = \"local\"\nbogus = 1\n").unwrap();
3769 assert!(Config::load(&path).is_err());
3770 std::fs::write(&path, "[release]\nmode = \"gha\"\n").unwrap();
3771 assert!(Config::load(&path).is_err());
3772 }
3773
3774 #[test]
3775 fn pre_gate_defaults_to_empty_and_the_starter_documents_it() {
3776 let dir = tempfile::tempdir().unwrap();
3777 let path = dir.path().join("magi.toml");
3778 std::fs::write(&path, Config::starter_toml()).unwrap();
3779 assert!(Config::load(&path).unwrap().verify.pre_gate.is_empty());
3780 assert!(Config::starter_toml().contains("# pre_gate = []"));
3781 }
3782
3783 #[test]
3784 fn release_version_files_parse_default_empty_and_are_validated() {
3785 let dir = tempfile::tempdir().unwrap();
3786 let path = dir.path().join("magi.toml");
3787 std::fs::write(&path, "").unwrap();
3788 assert!(
3789 Config::load(&path)
3790 .unwrap()
3791 .release
3792 .version_files
3793 .is_empty()
3794 );
3795 std::fs::write(
3796 &path,
3797 "[release]\nversion_files = [\n{ path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n{ path = \"package.json\", kind = \"json\" },\n]\n",
3798 )
3799 .unwrap();
3800 let files = Config::load(&path).unwrap().release.version_files;
3801 assert_eq!(files.len(), 2);
3802 assert_eq!(files[1].kind, VersionKind::Json);
3803 for bad in [
3804 "{ path = \"package.json\", kind = \"json\" }",
3805 "{ path = \"../Cargo.toml\", kind = \"cargo\" }",
3806 "{ path = \"Cargo.toml\", kind = \"cargo\", extra = 1 }",
3807 "{ path = \"Cargo.toml\", kind = \"yaml\" }",
3808 ] {
3809 std::fs::write(&path, format!("[release]\nversion_files = [{bad}]\n")).unwrap();
3810 assert!(Config::load(&path).is_err(), "{bad}");
3811 }
3812 assert!(Config::starter_toml().contains("# version_files = ["));
3813 }
3814
3815 #[test]
3816 fn starter_toml_explains_inherited_and_explicit_verify_timeouts() {
3817 let starter = Config::starter_toml();
3818 assert!(starter.contains("When timeout_verify is omitted, E2E and"));
3819 assert!(starter.contains("verification independent if timeout_review changes later"));
3820 assert!(starter.contains("# timeout_verify = 1200"));
3821 }
3822
3823 #[test]
3824 fn starter_toml_documents_chat_personas() {
3825 let starter = Config::starter_toml();
3826 assert!(starter.contains("# [[talk.personas]]"));
3827 assert!(starter.contains("tone only"));
3828 }
3829
3830 #[test]
3831 fn talk_personas_parse_and_are_validated() {
3832 let dir = tempfile::tempdir().unwrap();
3833 let path = dir.path().join("magi.toml");
3834 std::fs::write(
3835 &path,
3836 "[[talk.personas]]\nid = \"rei\"\nname = \"Quiet\"\nprompt = \"Be brief.\"\n\n\
3837 [[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n",
3838 )
3839 .unwrap();
3840 let cfg = Config::load(&path).expect("loads");
3841 assert_eq!(cfg.talk.personas.len(), 2);
3842 let catalog = crate::persona::catalog(&cfg.talk.personas);
3843 let rei = catalog.iter().find(|p| p.id == "rei").unwrap();
3844 assert_eq!(
3845 (rei.name.as_str(), rei.prompt.as_str()),
3846 ("Quiet", "Be brief.")
3847 );
3848 assert_eq!(catalog.last().unwrap().id, "gendo");
3849
3850 for (body, needle) in [
3851 (
3852 "[[talk.personas]]\nid = \"\"\nname = \"n\"\nprompt = \"p\"\n",
3853 "empty `id`",
3854 ),
3855 (
3856 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \" \"\n",
3857 "empty `prompt`",
3858 ),
3859 (
3860 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n\
3861 [[talk.personas]]\nid = \"a\"\nname = \"m\"\nprompt = \"q\"\n",
3862 "more than once",
3863 ),
3864 (
3865 "[[talk.personas]]\nid = \"default\"\nname = \"n\"\nprompt = \"p\"\n",
3866 "cannot be redefined",
3867 ),
3868 ] {
3869 std::fs::write(&path, body).unwrap();
3870 let err = format!("{:#}", Config::load(&path).unwrap_err());
3871 assert!(err.contains(needle), "{needle}: {err}");
3872 }
3873 }
3874
3875 #[test]
3876 fn talk_operator_name_is_trimmed_and_validated() {
3877 let dir = tempfile::tempdir().unwrap();
3878 let path = dir.path().join("magi.toml");
3879 let load = |body: &str| {
3880 std::fs::write(&path, body).unwrap();
3881 Config::load(&path)
3882 };
3883 let ok = load("[talk]\noperator_name = \" Commander \"\n").expect("ok");
3884 assert_eq!(ok.talk.operator_name(), Some("Commander"));
3885 let blank = load("[talk]\noperator_name = \" \"\n").expect("blank");
3886 assert_eq!(blank.talk.operator_name(), None);
3887 assert!(load("[talk]\noperator_name = \"a\\nb\"\n").is_err());
3888 let long = "x".repeat(65);
3889 assert!(load(&format!("[talk]\noperator_name = \"{long}\"\n")).is_err());
3890 }
3891
3892 #[test]
3893 fn talk_persona_icon_parses_and_a_bad_shape_keeps_config_usable() {
3894 let dir = tempfile::tempdir().unwrap();
3895 let load = |body: &str| {
3896 let path = dir.path().join("c.toml");
3897 std::fs::write(&path, body).unwrap();
3898 Config::load(&path)
3899 };
3900 let ok = load(
3901 "[[talk.personas]]\nid = \"rei\"\nicon = \"~/rei.png\"\n\n\
3902 [[talk.personas]]\nid = \"default\"\nicon = \"data:image/png;base64,AAAA\"\n",
3903 )
3904 .unwrap();
3905 let c = crate::persona::catalog(&ok.talk.personas);
3906 assert_eq!(c[0].icon.as_deref(), Some("data:image/png;base64,AAAA"));
3907 assert_eq!(c[2].icon.as_deref(), Some("~/rei.png"));
3908 assert!(c[2].prompt.contains("Rei"), "built-in voice kept");
3909 let oversized = format!(
3910 "data:image/png;base64,{}",
3911 "A".repeat(crate::persona_icon::ICON_MAX_BYTES)
3912 );
3913 for bad in ["", "rei.png", "/a/b.svg", "/a/../b.png", &oversized] {
3914 for (id, fields) in [
3915 ("rei", ""),
3916 ("default", ""),
3917 ("custom", "name = \"Custom\"\nprompt = \"Keep calm\"\n"),
3918 ] {
3919 let body = format!("[[talk.personas]]\nid = \"{id}\"\nicon = \"{bad}\"\n{fields}");
3920 let cfg = load(&body).expect("bad icon must not invalidate config");
3921 let persona = crate::persona::find(&cfg.talk.personas, id).unwrap();
3922 assert_eq!(persona.id, id);
3923 assert!(crate::persona_icon::load(bad).is_err());
3924 }
3925 }
3926 let doc = Config::starter_toml();
3927 assert!(doc.contains("# icon = "));
3928 }
3929
3930 #[test]
3931 fn talk_personas_in_two_layers_are_refused() {
3932 let dir = tempfile::tempdir().unwrap();
3933 let machine = dir.path().join("machine.toml");
3934 let repo = dir.path().join("repo.toml");
3935 let one = "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n";
3936 std::fs::write(&machine, one).unwrap();
3937 std::fs::write(&repo, one.replace("\"a\"", "\"b\"")).unwrap();
3938 let err = format!("{:#}", Config::load_layers(&[machine, repo]).unwrap_err());
3939 assert!(err.contains("talk.personas"), "{err}");
3940 }
3941
3942 #[test]
3943 fn starter_toml_documents_role_lists_as_backup_order() {
3944 let starter = Config::starter_toml();
3945 assert!(starter.contains("also an ordered backup list"));
3946 assert!(starter.contains("codex then sonnet are spares"));
3947 }
3948
3949 #[test]
3953 fn a_repository_can_declare_a_linear_history_merge_style() {
3954 let dir = tempfile::tempdir().unwrap();
3955 let path = dir.path().join("magi.toml");
3956 std::fs::write(&path, "[merge]\nmode = \"none\"\nstyle = \"squash\"\n").unwrap();
3957 let parsed = Config::load(&path).expect("config must load");
3958 assert_eq!(parsed.merge.style, MergeStyle::Squash);
3959 }
3960
3961 #[test]
3962 fn later_layers_win_and_vars_render() {
3963 let dir = tempfile::tempdir().unwrap();
3964 let machine = dir.path().join("machine.toml");
3965 let project = dir.path().join("magi.toml");
3966 std::fs::write(
3968 &machine,
3969 "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
3970 [graph]\ncandidates = 3\nmax_parallel = 8\n",
3971 )
3972 .unwrap();
3973 std::fs::write(
3976 &project,
3977 "[vars]\ncache = \"/shared\"\n\n\
3978 [graph]\ncandidates = 2\n\n\
3979 [verify]\ngate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
3980 )
3981 .unwrap();
3982
3983 let cfg = Config::load_layers(&[machine, project]).expect("layered load");
3984 assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
3985 assert_eq!(cfg.graph.implementers, 2, "project layer wins");
3986 assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
3987 assert_eq!(
3988 cfg.verify.gate,
3989 ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
3990 );
3991 assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
3993 }
3994
3995 #[test]
3996 fn talk_defaults_to_an_hour_and_an_unwritten_config_still_gets_it() {
3997 let g = Graph::default();
4001 assert_eq!(g.timeout_talk, 3600);
4002
4003 let dir = tempfile::tempdir().unwrap();
4004 let path = dir.path().join("magi.toml");
4005 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
4006 let cfg = Config::load(&path).expect("must load without timeout_talk set");
4007 assert_eq!(cfg.graph.timeout_talk, 3600);
4008 }
4009
4010 #[test]
4011 fn an_overridden_talk_timeout_reaches_the_loaded_config() {
4012 let dir = tempfile::tempdir().unwrap();
4013 let path = dir.path().join("magi.toml");
4014 std::fs::write(&path, "[graph]\ntimeout_talk = 120\n").unwrap();
4015 let cfg = Config::load(&path).expect("must load");
4016 assert_eq!(cfg.graph.timeout_talk, 120);
4017 }
4018
4019 #[test]
4020 fn the_disk_defaults_are_the_measurements_made_up_front() {
4021 let cfg = Config::default();
4022 assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
4023 assert!(cfg.disk.auto_fold);
4024 assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
4025 assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
4026 }
4027
4028 #[test]
4029 fn an_unset_disk_section_is_the_safe_default() {
4030 let dir = tempfile::tempdir().unwrap();
4031 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
4032 let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
4033 assert_eq!(cfg.disk, Disk::default());
4034 }
4035
4036 #[test]
4037 fn env_is_available_to_templates_with_a_default() {
4038 let dir = tempfile::tempdir().unwrap();
4039 let path = dir.path().join("magi.toml");
4040 std::fs::write(
4048 &path,
4049 "[verify]\n\
4050 gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
4051 \"populated={{ env | length > 0 }}\"]\n",
4052 )
4053 .unwrap();
4054 let cfg = Config::load(&path).expect("env lookup must render");
4055 assert_eq!(cfg.verify.gate[0], "cache=fallback");
4056 assert_eq!(cfg.verify.gate[1], "populated=true");
4057 }
4058
4059 #[test]
4060 fn a_broken_template_names_the_file() {
4061 let dir = tempfile::tempdir().unwrap();
4062 let path = dir.path().join("magi.toml");
4063 std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
4064 let err = Config::load(&path).expect_err("must not silently ignore");
4065 assert!(err.to_string().contains("teravars"), "{err}");
4066 }
4067
4068 #[test]
4069 fn tera_syntax_in_comments_is_inert() {
4070 let dir = tempfile::tempdir().unwrap();
4074 let path = dir.path().join("magi.toml");
4075 std::fs::write(
4076 &path,
4077 "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
4078 [graph]\ncandidates = 2\n",
4079 )
4080 .unwrap();
4081 let cfg = Config::load(&path).expect("comments must be inert, not rendered");
4082 assert_eq!(cfg.graph.implementers, 2);
4083 }
4084
4085 #[test]
4086 fn agent_turn_cap_round_trips_and_never_extends_the_budget() {
4087 use std::time::Duration;
4088
4089 let mut s: AgentSpec =
4090 toml::from_str("id = 'slow'\nkind = 'command'\ncommand = ['true']\n").unwrap();
4091 let budget = Duration::from_millis(1500);
4092 assert_eq!(s.max_turn_secs, None);
4093 assert_eq!(s.turn_timeout(budget), budget);
4094 assert!(!toml::to_string(&s).unwrap().contains("max_turn_secs"));
4095 for (cap, expected) in [
4096 (1, Duration::from_secs(1)),
4097 (2, budget),
4098 (0, Duration::ZERO),
4099 ] {
4100 s.max_turn_secs = Some(cap);
4101 let saved = toml::to_string(&s).unwrap();
4102 let loaded: AgentSpec = toml::from_str(&saved).unwrap();
4103 assert_eq!(loaded.max_turn_secs, Some(cap));
4104 assert_eq!(loaded.turn_timeout(budget), expected);
4105 }
4106 }
4107
4108 #[test]
4109 fn opencode_defaults_to_file_delivery() {
4110 let mut s = spec("oc");
4111 s.kind = AgentKind::Opencode;
4112 assert_eq!(s.delivery(), Delivery::File);
4113 s.prompt_delivery = Some(Delivery::Argv);
4114 assert_eq!(s.delivery(), Delivery::Argv);
4115 }
4116 #[test]
4117 fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
4118 let g = Graph::default();
4123 assert!(
4124 g.land,
4125 "stopping at an open PR left the watching to a human"
4126 );
4127 assert!(
4128 g.land_approval,
4129 "on-by-default land is only defensible while this is also on"
4130 );
4131 assert!(g.land_rounds > 0, "a loop with no budget never terminates");
4132 assert!(
4133 g.hold_contested_merge,
4134 "a contested hand-off must still reach a human when approvals are off"
4135 );
4136 }
4137 #[test]
4138 fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
4139 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]\nimplementers = [\"a\", \"b\"]\n").unwrap();
4146 std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
4147
4148 let err = Config::load_layers(&[machine.clone(), repo.clone()])
4149 .expect_err("two layers naming one array must not merge silently");
4150 assert_eq!(
4151 err.downcast_ref::<ConfigFailure>().unwrap().stage,
4152 "config-merge"
4153 );
4154 let err = err.to_string();
4155 assert!(err.contains("roles.implementers"), "{err}");
4156 assert!(err.contains("machine.toml"), "{err}");
4159 assert!(err.contains("magi.toml"), "{err}");
4160 }
4161
4162 #[test]
4163 fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
4164 let dir = tempfile::tempdir().unwrap();
4167 let machine = dir.path().join("machine.toml");
4168 let repo = dir.path().join("magi.toml");
4169 std::fs::write(&machine, "[roles]\nchatter = \"opus\"\n").unwrap();
4170 std::fs::write(
4171 &repo,
4172 "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
4173 [roles]\nimplementers = [\"oc\"]\n",
4174 )
4175 .unwrap();
4176
4177 let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
4178 assert_eq!(primary(cfg.roles.chatter.as_ref()), Some("opus"));
4179 assert_eq!(cfg.roles.implementers, ["oc"]);
4180 assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
4181 }
4182
4183 #[test]
4184 fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
4185 let dir = tempfile::tempdir().unwrap();
4188 let machine = dir.path().join("machine.toml");
4189 let repo = dir.path().join("magi.toml");
4190 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
4191 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4192
4193 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4194 assert_eq!(
4195 cfg.verify.gate,
4196 [
4197 "editorconfig-checker".to_owned(),
4198 "cargo make check".to_owned()
4199 ],
4200 "low-priority (machine) command first, high-priority (repo) command after"
4201 );
4202 }
4203
4204 fn load_one(body: &str) -> Result<Config> {
4205 let dir = tempfile::tempdir().unwrap();
4206 let path = dir.path().join("magi.toml");
4207 std::fs::write(&path, body).unwrap();
4208 Config::load_layers(&[path])
4209 }
4210
4211 #[test]
4212 fn pre_clean_config_is_strict_and_single_layer() {
4213 assert!(Config::default().worktree.pre_clean.is_empty());
4214 let good = load_one("[worktree]\npre_clean = [{run = 'cleanup', timeout_secs = 60}]\n");
4215 assert_eq!(good.unwrap().worktree.pre_clean[0].timeout_secs, Some(60));
4216 for bad in [
4217 "{}",
4218 "{run = ''}",
4219 "{run = ' ', timeout_secs = 2}",
4220 "{run = 'x', timeout_secs = 0}",
4221 "{run = 'x', timeout_secs = -1}",
4222 "{copy = 'cache'}",
4223 "{run = 'x', optional = true}",
4224 "'x'",
4225 ] {
4226 assert!(
4227 load_one(&format!("[worktree]\npre_clean = [{bad}]\n")).is_err(),
4228 "{bad}"
4229 );
4230 }
4231 let dir = tempfile::tempdir().unwrap();
4232 let a = dir.path().join("a.toml");
4233 let b = dir.path().join("b.toml");
4234 for path in [&a, &b] {
4235 std::fs::write(path, "[worktree]\npre_clean = [{run = 'cleanup'}]\n").unwrap();
4236 }
4237 assert!(
4238 Config::load_layers(&[a, b])
4239 .unwrap_err()
4240 .to_string()
4241 .contains("worktree.pre_clean")
4242 );
4243 }
4244
4245 #[test]
4246 fn worktree_setup_defaults_to_empty_and_parses_steps() {
4247 assert!(Config::default().worktree.setup.is_empty());
4248 let cfg = load_one(
4249 "[worktree]\nsetup = [\n { copy = \".env.example -> .env\" },\n \
4250 { copy = \"x\", optional = true },\n { run = \"true\", timeout_secs = 5 },\n]\n",
4251 )
4252 .unwrap();
4253 assert_eq!(cfg.worktree.setup.len(), 3);
4254 assert!(cfg.worktree.setup[1].optional);
4255 assert_eq!(cfg.worktree.setup[2].timeout_secs, Some(5));
4256 }
4257
4258 #[test]
4259 fn worktree_setup_rejects_malformed_steps() {
4260 for bad in [
4261 "{ copy = \"a\", run = \"b\" }",
4262 "{ optional = true }",
4263 "{ copy = \"a -> ../b\" }",
4264 "{ copy = \"a -> /abs\" }",
4265 "{ copy = \"a -> .git/config\" }",
4266 "{ run = \"b\", optional = true }",
4267 "{ copy = \"a\", timeout_secs = 3 }",
4268 "{ run = \"b\", bogus = 1 }",
4269 ] {
4270 let body = format!("[worktree]\nsetup = [{bad}]\n");
4271 assert!(load_one(&body).is_err(), "{bad}");
4272 }
4273 }
4274
4275 #[test]
4276 fn worktree_setup_in_two_layers_is_refused() {
4277 let dir = tempfile::tempdir().unwrap();
4278 let machine = dir.path().join("machine.toml");
4279 let repo = dir.path().join("magi.toml");
4280 std::fs::write(&machine, "[worktree]\nsetup = [{ run = \"a\" }]\n").unwrap();
4281 std::fs::write(&repo, "[worktree]\nsetup = [{ run = \"b\" }]\n").unwrap();
4282 assert!(Config::load_layers(&[machine, repo]).is_err());
4283 }
4284
4285 #[test]
4286 fn starter_toml_documents_worktree_setup() {
4287 let starter = Config::starter_toml();
4288 assert!(starter.contains("# [worktree]") && starter.contains("setup = ["));
4289 let body = starter.replace("# [worktree]", "[worktree]");
4291 let mut out = String::new();
4292 let mut live = false;
4293 for line in body.lines() {
4294 if line == "[worktree]" {
4295 live = true;
4296 } else if live && !line.starts_with("# ") {
4297 live = false;
4298 }
4299 out.push_str(&if live {
4300 line.replacen("# ", "", 1)
4301 } else {
4302 line.to_owned()
4303 });
4304 out.push('\n');
4305 }
4306 let cfg = load_one(&out).expect("uncommented example loads");
4307 assert_eq!(cfg.worktree.setup.len(), 3);
4308 }
4309
4310 #[test]
4311 fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
4312 let dir = tempfile::tempdir().unwrap();
4313 let machine = dir.path().join("machine.toml");
4314 let repo = dir.path().join("magi.toml");
4315 std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
4316 std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
4317
4318 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4319 assert_eq!(
4320 cfg.verify.e2e,
4321 ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
4322 );
4323 }
4324
4325 #[test]
4326 fn two_layers_declaring_repos_roots_are_both_scanned() {
4327 let dir = tempfile::tempdir().unwrap();
4328 let machine = dir.path().join("machine.toml");
4329 let repo = dir.path().join("magi.toml");
4330 std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
4331 std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
4332
4333 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4334 assert_eq!(
4335 cfg.repos.roots,
4336 [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
4337 );
4338 }
4339
4340 #[test]
4341 fn duplicate_gate_commands_across_layers_both_run() {
4342 let dir = tempfile::tempdir().unwrap();
4345 let machine = dir.path().join("machine.toml");
4346 let repo = dir.path().join("magi.toml");
4347 std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
4348 std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
4349
4350 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4351 assert_eq!(
4352 cfg.verify.gate,
4353 ["same-command".to_owned(), "same-command".to_owned()]
4354 );
4355 }
4356
4357 #[test]
4358 fn notify_command_is_still_refused_across_two_layers() {
4359 let dir = tempfile::tempdir().unwrap();
4361 let machine = dir.path().join("machine.toml");
4362 let repo = dir.path().join("magi.toml");
4363 std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
4364 std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
4365
4366 let err = Config::load_layers(&[machine.clone(), repo.clone()])
4367 .expect_err("an argv split across layers must not concatenate");
4368 assert_eq!(
4369 err.downcast_ref::<ConfigFailure>().unwrap().stage,
4370 "config-merge"
4371 );
4372 let err = err.to_string();
4373 assert!(err.contains("notify.command"), "{err}");
4374 assert!(err.contains("machine.toml"), "{err}");
4375 assert!(err.contains("magi.toml"), "{err}");
4376 }
4377
4378 #[test]
4379 fn one_layer_declaring_verify_gate_runs_unchanged() {
4380 let dir = tempfile::tempdir().unwrap();
4383 let path = dir.path().join("magi.toml");
4384 std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4385
4386 let cfg = Config::load(&path).expect("single layer must still load");
4387 assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
4388 }
4389
4390 #[test]
4391 fn layered_parse_failures_name_the_failing_input() {
4392 let dir = tempfile::tempdir().unwrap();
4393 let a = dir.path().join("a.toml");
4394 let b = dir.path().join("b.toml");
4395 std::fs::write(&a, "[graph").unwrap();
4396 std::fs::write(&b, "[verify").unwrap();
4397 let paths = [a.clone(), b.clone()];
4398 let first = Config::load_layers(&paths).unwrap_err();
4399 let first_cause = first.downcast_ref::<ConfigFailure>().unwrap();
4400 assert_eq!(first_cause.stage, "config-parse");
4401 assert_eq!(first_cause.target, serde_json::to_string(&[&a]).unwrap());
4402 std::fs::write(&a, "").unwrap();
4403 let second = Config::load_layers(&paths).unwrap_err();
4404 let second_cause = second.downcast_ref::<ConfigFailure>().unwrap();
4405 assert_eq!(second_cause.stage, "config-parse");
4406 assert_eq!(second_cause.target, serde_json::to_string(&[&b]).unwrap());
4407 assert_ne!(first_cause.target, second_cause.target);
4408 }
4409
4410 #[test]
4411 fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
4412 let dir = tempfile::tempdir().unwrap();
4413 let machine = dir.path().join("machine.toml");
4414 let repo = dir.path().join("magi.toml");
4415 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
4416 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4417 let paths = vec![machine.clone(), repo.clone()];
4418
4419 let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
4420 let described =
4421 Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
4422 assert!(described.contains("editorconfig-checker && cargo make check"));
4423 assert!(
4424 described.contains(&machine.display().to_string()),
4425 "{described}"
4426 );
4427 assert!(
4428 described.contains(&repo.display().to_string()),
4429 "{described}"
4430 );
4431
4432 let single = vec![repo.clone()];
4434 let solo_cfg = Config::load_layers(&single).expect("single layer loads");
4435 let solo_described =
4436 Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
4437 assert_eq!(solo_described, "cargo make check");
4438 }
4439
4440 mod remote_layers {
4441 use super::*;
4442
4443 fn git(dir: &Path, args: &[&str]) {
4444 use crate::proc::Quiet as _;
4445 let out = std::process::Command::new("git")
4446 .args(args)
4447 .quiet()
4448 .current_dir(dir)
4449 .output()
4450 .unwrap();
4451 assert!(out.status.success(), "git {args:?}: {out:?}");
4452 }
4453
4454 fn fixture(remote: &str, disk: &str) -> (tempfile::TempDir, PathBuf) {
4457 let tmp = tempfile::tempdir().unwrap();
4458 let bare = tmp.path().join("o.git");
4459 git(tmp.path(), &["init", "--bare", "-b", "trunk", "o.git"]);
4460 let repo = tmp.path().join("repo");
4461 std::fs::create_dir_all(&repo).unwrap();
4462 git(&repo, &["init", "-b", "trunk"]);
4463 git(&repo, &["config", "user.name", "t"]);
4464 git(&repo, &["config", "user.email", "t@example.com"]);
4465 std::fs::write(repo.join("magi.toml"), remote).unwrap();
4466 git(&repo, &["add", "-A"]);
4467 git(&repo, &["commit", "-m", "x"]);
4468 git(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
4469 git(&repo, &["push", "origin", "trunk"]);
4470 git(&repo, &["fetch", "origin"]);
4471 git(&repo, &["remote", "set-head", "origin", "trunk"]);
4472 std::fs::write(repo.join("magi.toml"), disk).unwrap();
4473 (tmp, repo)
4474 }
4475
4476 #[tokio::test]
4477 async fn branch_owner_holds_only_add_literal_true_values() {
4478 for (text, expected) in [
4479 ("[graph]\nland_approval = true\n", true),
4480 ("[graph]\nland_approval = false\n", false),
4481 ("[graph]\nland = true\n", false),
4482 ("[graph\n", false),
4483 ("[graph]\nland_approval = \"yes\"\n", false),
4484 ("[graph]\nland_approval = 1\n", false),
4485 ] {
4486 let (_tmp, repo) = fixture(text, "[graph]\nland_approval = false\n");
4487 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
4488 let (holds, _) = branch_owner_holds(&repo, &head).await;
4489 assert_eq!(
4490 holds.contains(&(OwnerHold::LandApproval, "magi.toml".into())),
4491 expected
4492 );
4493 assert!(
4494 !holds
4495 .iter()
4496 .any(|(h, _)| *h == OwnerHold::HoldContestedMerge)
4497 );
4498 for base in [false, true] {
4499 let mut cfg = Config::default();
4500 cfg.graph.land_approval = base;
4501 let mut state = crate::run::RunState::new(
4502 repo.clone(),
4503 "trunk".into(),
4504 head.clone(),
4505 "review".into(),
4506 cfg,
4507 );
4508 state.observe_branch_owner_holds(&head).await;
4509 assert!(
4510 state.branch_owner_holds.is_empty(),
4511 "competition candidates are excluded"
4512 );
4513 state.reviewed_commits = Some(Vec::new());
4514 state.observe_branch_owner_holds(&head).await;
4515 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base || expected);
4516 }
4517 }
4518 }
4519
4520 #[tokio::test]
4521 async fn branch_owner_holds_missing_and_unreadable_preserve_base() {
4522 let (_tmp, repo) = fixture(
4523 "[graph]\nland_approval = true\n",
4524 "[graph]\nland_approval = true\n",
4525 );
4526 git(&repo, &["rm", "magi.toml"]);
4527 std::fs::create_dir(repo.join(".magi")).unwrap();
4528 std::fs::write(
4529 repo.join(".magi/config.toml"),
4530 "[graph]\nhold_contested_merge = true\n",
4531 )
4532 .unwrap();
4533 git(&repo, &["add", "."]);
4534 git(&repo, &["commit", "-m", "nested hold"]);
4535 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
4536 let (holds, _) = branch_owner_holds(&repo, &head).await;
4537 assert_eq!(
4538 holds,
4539 [(OwnerHold::HoldContestedMerge, ".magi/config.toml".into())]
4540 );
4541 let (holds, diagnostics) =
4542 branch_owner_holds(&repo, "0000000000000000000000000000000000000000").await;
4543 assert!(holds.is_empty());
4544 assert!(!diagnostics.is_empty());
4545 let (holds, diagnostics) = branch_owner_holds(&repo, "").await;
4546 assert!(holds.is_empty());
4547 assert!(!diagnostics.is_empty());
4548 for base in [false, true] {
4549 let mut cfg = Config::default();
4550 cfg.graph.land_approval = base;
4551 let mut state = crate::run::RunState::new(
4552 repo.clone(),
4553 "trunk".into(),
4554 head.clone(),
4555 "review".into(),
4556 cfg,
4557 );
4558 state.reviewed_commits = Some(Vec::new());
4559 state.observe_branch_owner_holds(&head).await;
4560 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
4561 state
4562 .observe_branch_owner_holds("0000000000000000000000000000000000000000")
4563 .await;
4564 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
4565 }
4566 }
4567
4568 #[test]
4569 fn reads_the_remote_blob_not_the_working_tree() {
4570 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4571 let (cfg, _) = Config::discover(&repo, None).unwrap();
4572 assert_eq!(cfg.graph.implementers, 2);
4573 }
4574
4575 #[test]
4576 fn detached_head_still_reads_the_remote() {
4577 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4578 git(&repo, &["checkout", "--detach"]);
4579 let (cfg, _) = Config::discover(&repo, None).unwrap();
4580 assert_eq!(cfg.graph.implementers, 2);
4581 }
4582
4583 #[test]
4584 fn a_missing_ref_is_an_error_not_a_fallback() {
4585 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4586 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
4587 let err = format!("{:#}", Config::discover(&repo, None).unwrap_err());
4588 assert!(err.contains("origin"), "{err}");
4589 }
4590
4591 #[test]
4592 fn merge_base_in_the_checkout_locates_the_ref() {
4593 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
4594 assert!(Config::discover(&repo, None).is_err());
4595 }
4596
4597 #[test]
4598 fn the_magi_dir_layer_is_read_too() {
4599 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4600 std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
4601 std::fs::create_dir_all(repo.join(".magi")).unwrap();
4602 std::fs::write(repo.join(".magi/config.toml"), "[graph]\njudges = 3\n").unwrap();
4603 git(&repo, &["add", "-A"]);
4604 git(&repo, &["commit", "-m", "y"]);
4605 git(&repo, &["push", "origin", "trunk"]);
4606 git(&repo, &["fetch", "origin"]);
4607 let (cfg, layers) = Config::discover(&repo, None).unwrap();
4608 assert_eq!((cfg.graph.implementers, cfg.graph.judges), (2, 3));
4609 assert_eq!(layers.len(), 2);
4610 }
4611
4612 #[test]
4613 fn an_include_in_a_repository_layer_resolves_against_the_same_commit() {
4614 let (_t, repo) = fixture("include = [\"gate.toml\"]\n", "");
4615 std::fs::write(repo.join("magi.toml"), "include = [\"gate.toml\"]\n").unwrap();
4616 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 2\n").unwrap();
4617 git(&repo, &["add", "-A"]);
4618 git(&repo, &["commit", "-m", "inc"]);
4619 git(&repo, &["push", "origin", "trunk"]);
4620 git(&repo, &["fetch", "origin"]);
4621 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 9\n").unwrap();
4623 let (cfg, _) = Config::discover(&repo, None).unwrap();
4624 assert_eq!(cfg.graph.implementers, 2);
4625 }
4626
4627 #[test]
4628 fn a_machine_layer_base_is_rendered_before_locating_the_ref() {
4629 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
4630 let m = t.path().join("machine.toml");
4631 std::fs::write(
4632 &m,
4633 "[merge]\nbase = \"{{ env.MAGI_TEST_NO_SUCH | default(value='trunk') }}\"\n",
4634 )
4635 .unwrap();
4636 let (remote, base) = {
4637 let probe = probe_merge(&m, &repo).unwrap();
4638 (probe.remote, probe.base)
4639 };
4640 assert_eq!((remote, base), (None, Some("trunk".to_owned())));
4641 }
4642
4643 #[test]
4644 fn a_machine_layer_base_sees_the_checkouts_repo_name() {
4645 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4646 let m = t.path().join("machine.toml");
4647 std::fs::write(&m, "[merge]\nbase = \"{{ repo_name }}\"\n").unwrap();
4648 let probe = probe_merge(&m, &repo).unwrap();
4649 assert_eq!(probe.base.as_deref(), Some("repo"));
4650 }
4651
4652 #[test]
4653 fn every_include_form_is_recognised() {
4654 assert!(declares_include("include = [\"a.toml\"]\n"));
4655 assert!(declares_include("\"include\" = [\"a.toml\"]\n"));
4656 assert!(declares_include("teravars = { include = [\"a.toml\"] }\n"));
4657 assert!(declares_include("[teravars]\ninclude = [\"a.toml\"]\n"));
4658 assert!(!declares_include("[graph]\ncandidates = 2\n"));
4659 }
4660
4661 #[test]
4662 fn an_explicit_config_is_read_as_named() {
4663 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4664 let own = t.path().join("own.toml");
4665 std::fs::write(&own, "[graph]\ncandidates = 4\n").unwrap();
4666 let (cfg, _) = Config::discover(&repo, Some(&own)).unwrap();
4667 assert_eq!(cfg.graph.implementers, 4);
4668 }
4669
4670 #[test]
4671 fn discover_fetched_fails_when_the_fetch_does() {
4672 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4673 std::fs::remove_dir_all(t.path().join("o.git")).unwrap();
4674 let rt = tokio::runtime::Builder::new_current_thread()
4675 .enable_all()
4676 .build()
4677 .unwrap();
4678 let err = rt
4679 .block_on(Config::discover_fetched(&repo, None))
4680 .unwrap_err();
4681 assert!(format!("{err:#}").contains("fetch"), "{err:#}");
4682 }
4683
4684 #[test]
4685 fn fetch_and_remote_parse_failures_have_distinct_verified_causes() {
4686 let (tmp, repo) = fixture("[graph\ncandidates = 2\n", "");
4687 let remote = tmp.path().join("o.git");
4688 let offline = tmp.path().join("offline.git");
4689 std::fs::rename(&remote, &offline).unwrap();
4690 let rt = tokio::runtime::Builder::new_current_thread()
4691 .enable_all()
4692 .build()
4693 .unwrap();
4694 let fetch = rt
4695 .block_on(Config::discover_fetched(&repo, None))
4696 .unwrap_err();
4697 let fetch_cause = fetch.downcast_ref::<ConfigFailure>().unwrap();
4698 assert_eq!(fetch_cause.stage, "config-fetch");
4699 assert_eq!(fetch_cause.target, "origin/trunk");
4700
4701 std::fs::rename(&offline, &remote).unwrap();
4702 let parse = rt
4703 .block_on(Config::discover_fetched(&repo, None))
4704 .unwrap_err();
4705 let parse_cause = parse.downcast_ref::<ConfigFailure>().unwrap();
4706 assert_eq!(parse_cause.stage, "config-parse");
4707 assert!(parse_cause.target.contains("magi.toml"));
4708 assert!(
4709 !parse_cause.target.contains("/magi/config/"),
4710 "cache commit paths are incidental"
4711 );
4712 assert_ne!(fetch_cause.stage, parse_cause.stage);
4713 }
4714
4715 #[test]
4716 fn discover_fetched_survives_a_fetch_that_leaves_no_origin_head() {
4717 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4720 git(&repo, &["remote", "set-head", "origin", "-d"]);
4721 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
4722 git(
4723 &repo,
4724 &["config", "remote.origin.followRemoteHEAD", "never"],
4725 );
4726 let rt = tokio::runtime::Builder::new_current_thread()
4727 .enable_all()
4728 .build()
4729 .unwrap();
4730 let (cfg, _) = rt.block_on(Config::discover_fetched(&repo, None)).unwrap();
4731 assert_eq!(cfg.graph.implementers, 2);
4732 }
4733
4734 #[test]
4735 fn a_non_git_directory_reads_its_files() {
4736 let dir = tempfile::tempdir().unwrap();
4737 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 4\n").unwrap();
4738 let (cfg, _) = Config::discover(dir.path(), None).unwrap();
4739 assert_eq!(cfg.graph.implementers, 4);
4740 }
4741 }
4742
4743 #[test]
4744 fn github_language_defaults_to_english_and_accepts_japanese() {
4745 let default: Graph = toml::from_str("").unwrap();
4746 assert_eq!(default.github_language, "en");
4747 assert!(default.github_english() && default.language_gate());
4748 let ja: Graph = toml::from_str("github_language = \"ja\"").unwrap();
4749 assert!(!ja.github_english() && !ja.language_gate());
4750 let only_ops: Graph = toml::from_str("language = \"ja\"").unwrap();
4752 assert!(only_ops.language_gate());
4753 let off: Graph = toml::from_str("github_text_guard = false").unwrap();
4754 assert!(!off.language_gate() && off.github_english());
4755 assert!(Config::starter_toml().contains("github_language = \"en\""));
4756 }
4757}