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