1use std::collections::BTreeMap;
44use std::path::{Path, PathBuf};
45
46use anyhow::{Context as _, Result, bail};
47use serde::{Deserialize, Serialize};
48
49#[derive(Debug, thiserror::Error)]
52#[error("{stage}: {target}")]
53pub(crate) struct ConfigFailure {
54 pub(crate) stage: &'static str,
55 pub(crate) target: String,
56}
57
58impl ConfigFailure {
59 fn render(error: &teravars::Error, paths: &[PathBuf]) -> Self {
60 let stage = match error {
61 teravars::Error::Io(_) => "config-read",
62 teravars::Error::Toml(_) | teravars::Error::Extract(_) => "config-parse",
63 teravars::Error::Render(_) => "config-template",
64 teravars::Error::IncludeCycle { .. } | teravars::Error::IncludeConflict { .. } => {
65 "config-include"
66 }
67 _ => "config-render",
68 };
69 Self::layers(stage, paths)
70 }
71
72 fn layers(stage: &'static str, paths: &[PathBuf]) -> Self {
73 let targets: Vec<_> = paths
74 .iter()
75 .map(|path| {
76 path.ancestors()
79 .find(|p| p.join(REPO_MARKER).is_file())
80 .and_then(|root| path.strip_prefix(root).ok())
81 .unwrap_or(path)
82 .to_string_lossy()
83 .into_owned()
84 })
85 .collect();
86 Self {
87 stage,
88 target: serde_json::to_string(&targets).expect("config paths"),
89 }
90 }
91}
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
95#[serde(rename_all = "lowercase")]
96pub enum AgentKind {
97 Claude,
99 Opencode,
101 Antigravity,
105 Codex,
109 Omp,
115 Command,
117}
118
119impl AgentKind {
120 pub fn program(self) -> Option<&'static str> {
122 match self {
123 Self::Claude => Some("claude"),
124 Self::Opencode => Some("opencode"),
125 Self::Antigravity => Some("agy"),
126 Self::Codex => Some("codex"),
127 Self::Omp => Some("omp"),
128 Self::Command => None,
129 }
130 }
131
132 pub fn as_str(self) -> &'static str {
134 match self {
135 Self::Claude => "claude",
136 Self::Opencode => "opencode",
137 Self::Antigravity => "antigravity",
138 Self::Codex => "codex",
139 Self::Omp => "omp",
140 Self::Command => "command",
141 }
142 }
143
144 pub const ALL: [Self; 6] = [
152 Self::Claude,
153 Self::Opencode,
154 Self::Antigravity,
155 Self::Codex,
156 Self::Omp,
157 Self::Command,
158 ];
159}
160
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
163#[serde(rename_all = "lowercase")]
164pub enum Delivery {
165 Stdin,
167 Argv,
169 File,
171}
172
173#[derive(Debug, Clone, Deserialize, Serialize)]
175#[serde(deny_unknown_fields)]
176pub struct AgentSpec {
177 pub id: String,
179 pub kind: AgentKind,
181 #[serde(default)]
183 pub model: Option<String>,
184 #[serde(default)]
187 pub command: Vec<String>,
188 #[serde(default)]
190 pub extra_args: Vec<String>,
191 #[serde(default)]
193 pub env: BTreeMap<String, String>,
194 #[serde(default)]
196 pub prompt_delivery: Option<Delivery>,
197 #[serde(default, skip_serializing_if = "Option::is_none")]
200 pub max_turn_secs: Option<u64>,
201}
202
203impl AgentSpec {
204 pub fn turn_timeout(&self, budget: std::time::Duration) -> std::time::Duration {
206 self.max_turn_secs.map_or(budget, |secs| {
207 budget.min(std::time::Duration::from_secs(secs))
208 })
209 }
210
211 pub fn delivery(&self) -> Delivery {
217 self.prompt_delivery.unwrap_or(match self.kind {
218 AgentKind::Claude | AgentKind::Command => Delivery::Stdin,
219 AgentKind::Codex => Delivery::Stdin,
223 AgentKind::Omp => Delivery::Stdin,
227 AgentKind::Opencode | AgentKind::Antigravity => Delivery::File,
228 })
229 }
230
231 pub fn display(&self) -> String {
233 match &self.model {
234 Some(m) => format!("{} ({}:{m})", self.id, self.kind.as_str()),
235 None => format!("{} ({})", self.id, self.kind.as_str()),
236 }
237 }
238}
239
240#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
247#[serde(untagged)]
248pub enum AgentChoice {
249 One(String),
251 Chain(Vec<String>),
253}
254
255impl AgentChoice {
256 pub fn ids(&self) -> Vec<&str> {
258 let all: Vec<&str> = match self {
259 Self::One(id) => vec![id.as_str()],
260 Self::Chain(ids) => ids.iter().map(String::as_str).collect(),
261 };
262 all.into_iter()
263 .map(str::trim)
264 .filter(|id| !id.is_empty())
265 .collect()
266 }
267
268 pub fn primary(&self) -> Option<&str> {
270 self.ids().into_iter().next()
271 }
272}
273
274impl From<&str> for AgentChoice {
275 fn from(id: &str) -> Self {
276 Self::One(id.to_owned())
277 }
278}
279
280pub fn primary(choice: Option<&AgentChoice>) -> Option<&str> {
282 choice.and_then(AgentChoice::primary)
283}
284
285#[derive(Debug, Clone, Default, Deserialize, Serialize)]
288#[serde(deny_unknown_fields, default)]
289pub struct Roles {
290 pub implementers: Vec<String>,
292 pub judges: Vec<String>,
294 pub reviewers: Vec<String>,
296 pub fixer: Option<AgentChoice>,
305 pub chatter: Option<AgentChoice>,
319 pub dupes_judge: Option<AgentChoice>,
323 pub conductor: Option<AgentChoice>,
336 pub advisors: Vec<String>,
347 pub synthesizer: Option<AgentChoice>,
360 pub language_judge: Option<AgentChoice>,
369}
370
371#[derive(Debug, Clone, Deserialize, Serialize)]
373#[serde(deny_unknown_fields, default)]
374pub struct Graph {
375 pub github_text_guard: bool,
377 pub github_language: String,
383 #[serde(alias = "candidates")]
415 pub implementers: usize,
416 #[serde(default)]
418 pub selected_implementer: Option<String>,
419 pub judges: usize,
421 pub deliberate_rounds: usize,
423 pub reviewers: usize,
431 pub review_rounds: usize,
433 pub gate_fix_rounds: usize,
439 pub max_parallel: usize,
441 pub language: String,
443 pub sessions: bool,
451 pub timeout_implement: u64,
453 pub timeout_judge: u64,
455 pub timeout_review: u64,
457 pub timeout_verify: Option<u64>,
466 pub timeout_fix: u64,
468 pub timeout_talk: u64,
476 pub timeout_resource_wait: u64,
485 pub retries: usize,
487 pub worktree_root: Option<PathBuf>,
489 pub land: bool,
502 pub land_rounds: usize,
504 pub rerun_flaky_checks: bool,
512 pub land_approval: bool,
523 pub hold_contested_merge: bool,
534 pub question_routing: bool,
539 pub file_followups: bool,
546 pub release_deputy_followups: bool,
554 pub answer_timeout: u64,
558 pub incomplete_review: IncompleteReviewPolicy,
561 pub e2e_every_round: bool,
579 pub advise: bool,
593 pub advisors: usize,
598 pub graft_runner_up: bool,
607}
608
609impl Default for Graph {
610 fn default() -> Self {
611 Self {
612 github_text_guard: true,
613 github_language: "en".into(),
614 implementers: 1,
615 selected_implementer: None,
616 judges: 3,
617 deliberate_rounds: 1,
618 reviewers: 3,
619 review_rounds: 6,
620 gate_fix_rounds: 1,
621 max_parallel: 4,
622 language: "en".to_owned(),
623 sessions: true,
624 timeout_implement: 3600,
625 timeout_judge: 1200,
626 timeout_review: 1200,
627 timeout_verify: None,
628 timeout_fix: 1800,
629 timeout_talk: 3600,
630 timeout_resource_wait: 1800,
631 retries: 1,
632 worktree_root: None,
633 land: true,
634 land_rounds: 4,
635 rerun_flaky_checks: true,
636 land_approval: true,
637 hold_contested_merge: true,
638 question_routing: true,
639 file_followups: true,
640 release_deputy_followups: true,
641 answer_timeout: 86_400,
642 incomplete_review: IncompleteReviewPolicy::Block,
643 e2e_every_round: false,
644 advise: true,
645 advisors: 3,
646 graft_runner_up: true,
647 }
648 }
649}
650
651impl Graph {
652 pub fn verify_timeout(&self) -> u64 {
656 self.timeout_verify.unwrap_or(self.timeout_review)
657 }
658
659 pub fn language_gate(&self) -> bool {
662 self.github_text_guard && self.github_english()
663 }
664
665 pub fn github_english(&self) -> bool {
667 crate::lang::is_english(&self.github_language)
668 }
669}
670
671#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
678#[serde(rename_all = "lowercase")]
679pub enum IncompleteReviewPolicy {
680 Block,
684 Warn,
689}
690
691#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
693#[serde(rename_all = "lowercase")]
694pub enum LeakPolicy {
695 Warn,
697 Redact,
699 Fail,
701}
702
703#[derive(Debug, Clone, Deserialize, Serialize)]
710#[serde(deny_unknown_fields, default)]
711pub struct Blind {
712 pub commit_msg_hook: bool,
715 pub strip_lines: Vec<String>,
719 pub vendor_tokens: Vec<String>,
721 pub on_leak: LeakPolicy,
723 pub seed: Option<u64>,
726}
727
728impl Default for Blind {
729 fn default() -> Self {
730 Self {
731 commit_msg_hook: true,
732 strip_lines: [
733 "Co-Authored-By:",
734 "Signed-off-by:",
735 "Assisted-by:",
736 "Generated-by:",
737 "Generated with",
738 "\u{1f916}",
739 ]
740 .iter()
741 .map(|s| (*s).to_owned())
742 .collect(),
743 vendor_tokens: [
744 "claude",
745 "anthropic",
746 "codex",
747 "openai",
748 "chatgpt",
749 "gemini",
750 "grok",
751 "xai",
752 "copilot",
753 "opencode",
754 "qoder",
755 "cursor",
756 "\u{1f916}",
757 ]
758 .iter()
759 .map(|s| (*s).to_owned())
760 .collect(),
761 on_leak: LeakPolicy::Warn,
762 seed: None,
763 }
764 }
765}
766
767#[derive(Debug, Clone, Default, Deserialize, Serialize)]
769#[serde(deny_unknown_fields, default)]
770pub struct Verify {
771 pub e2e: Vec<String>,
774 pub gate: Vec<String>,
776 #[serde(default)]
785 pub pre_gate: Vec<String>,
786 pub shell: Option<Vec<String>>,
789}
790
791impl Verify {
792 pub fn cache_dir(&self) -> Option<PathBuf> {
798 self.e2e
799 .iter()
800 .chain(self.gate.iter())
801 .find_map(|cmd| crate::disk::extract_cargo_target_dir(cmd))
802 }
803
804 pub fn cargo_manifests(&self) -> Vec<PathBuf> {
807 let all: Vec<String> = self.e2e.iter().chain(self.gate.iter()).cloned().collect();
808 crate::cache::extract_manifest_paths(&all)
809 }
810}
811
812#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
814#[serde(deny_unknown_fields, default)]
815pub struct Worktree {
816 pub setup: Vec<SetupStep>,
819}
820
821#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
823#[serde(deny_unknown_fields, default)]
824pub struct SetupStep {
825 pub copy: Option<String>,
828 pub optional: bool,
830 pub run: Option<String>,
832 pub timeout_secs: Option<u64>,
835}
836
837impl Worktree {
838 pub fn validate(&self) -> Result<()> {
840 for (i, step) in self.setup.iter().enumerate() {
841 let n = i + 1;
842 match (&step.copy, &step.run) {
843 (Some(c), None) => {
844 if step.timeout_secs.is_some() {
845 bail!("[worktree] setup step {n}: `timeout_secs` applies to `run` only");
846 }
847 crate::worktree_setup::validate_copy(c)
848 .with_context(|| format!("[worktree] setup step {n}"))?;
849 }
850 (None, Some(r)) => {
851 if r.trim().is_empty() {
852 bail!("[worktree] setup step {n}: `run` is empty");
853 }
854 if step.optional {
855 bail!("[worktree] setup step {n}: `optional` applies to `copy` only");
856 }
857 }
858 _ => bail!("[worktree] setup step {n} must set exactly one of `copy` and `run`"),
859 }
860 }
861 Ok(())
862 }
863}
864
865#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
875#[serde(deny_unknown_fields, default)]
876pub struct Disk {
877 pub min_free_bytes: u64,
886 pub auto_fold: bool,
892 pub fold_grace_secs: u64,
900 pub cache_limit_bytes: u64,
912 pub worktree_limit_bytes: u64,
914 pub worktree_reclaim_bytes: u64,
916 pub retained_attempt_limit: usize,
920}
921
922impl Default for Disk {
923 fn default() -> Self {
924 Self {
925 min_free_bytes: 8 * 1024 * 1024 * 1024,
926 auto_fold: true,
927 fold_grace_secs: 6 * 60 * 60,
928 cache_limit_bytes: 10 * 1024 * 1024 * 1024,
929 worktree_limit_bytes: 10 * 1024 * 1024 * 1024,
930 worktree_reclaim_bytes: 16 * 1024 * 1024 * 1024,
931 retained_attempt_limit: 8,
932 }
933 }
934}
935
936#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
938#[serde(rename_all = "lowercase")]
939pub enum MergeMode {
940 None,
943 Local,
946 Pr,
950}
951
952#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
966#[serde(rename_all = "lowercase")]
967pub enum MergeStyle {
968 #[default]
973 Merge,
974 Squash,
980 Rebase,
986}
987
988#[derive(Debug, Clone, Deserialize, Serialize)]
990#[serde(deny_unknown_fields, default)]
991pub struct Merge {
992 pub mode: MergeMode,
995 pub base: Option<String>,
997 pub style: MergeStyle,
1000 pub remote: String,
1002 pub release_bump: bool,
1015}
1016
1017impl Default for Merge {
1018 fn default() -> Self {
1019 Self {
1020 mode: MergeMode::None,
1021 base: None,
1022 style: MergeStyle::default(),
1023 remote: "origin".to_owned(),
1024 release_bump: true,
1025 }
1026 }
1027}
1028
1029#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1031#[serde(rename_all = "lowercase")]
1032pub enum UpdateMode {
1033 Off,
1035 Notify,
1038 Install,
1040}
1041
1042#[derive(Debug, Clone, Deserialize, Serialize)]
1044#[serde(deny_unknown_fields, default)]
1045pub struct Update {
1046 pub mode: UpdateMode,
1048 pub interval: Option<String>,
1050 pub auto_restart: bool,
1052}
1053
1054impl Default for Update {
1055 fn default() -> Self {
1056 Self {
1057 mode: UpdateMode::Notify,
1058 interval: None,
1059 auto_restart: false,
1060 }
1061 }
1062}
1063
1064#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1066#[serde(rename_all = "lowercase")]
1067pub enum ReleaseMode {
1068 #[default]
1071 Actions,
1072 Local,
1076}
1077
1078#[derive(Debug, Clone, Deserialize, Serialize)]
1080#[serde(deny_unknown_fields, default)]
1081pub struct Release {
1082 pub mode: ReleaseMode,
1085 pub commands: Vec<String>,
1092 pub timeout_minutes: u64,
1094 pub version_files: Vec<VersionFile>,
1102}
1103
1104#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1106#[serde(rename_all = "lowercase")]
1107pub enum VersionKind {
1108 Cargo,
1110 Json,
1112}
1113
1114#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
1116#[serde(deny_unknown_fields)]
1117pub struct VersionFile {
1118 pub path: String,
1120 pub kind: VersionKind,
1122}
1123
1124impl Default for Release {
1125 fn default() -> Self {
1126 Self {
1127 mode: ReleaseMode::Actions,
1128 commands: Vec::new(),
1129 timeout_minutes: 30,
1130 version_files: Vec::new(),
1131 }
1132 }
1133}
1134
1135impl Release {
1136 pub fn validate(&self) -> Result<()> {
1138 crate::release_manifest::validate(&self.version_files).context("[release] version_files")
1139 }
1140
1141 pub fn is_local(&self) -> bool {
1143 self.mode == ReleaseMode::Local
1144 }
1145}
1146
1147#[derive(Debug, Clone, Deserialize, Serialize)]
1149#[serde(try_from = "CoordinationFields")]
1150pub struct Coordination {
1151 pub contract_file: String,
1153 pub contract_token: String,
1155 pub lock_file: String,
1157}
1158
1159#[derive(Deserialize, Default)]
1160#[serde(deny_unknown_fields, default)]
1161struct CoordinationFields {
1162 contract_file: String,
1163 contract_token: String,
1164 lock_file: String,
1165}
1166
1167impl TryFrom<CoordinationFields> for Coordination {
1168 type Error = anyhow::Error;
1169
1170 fn try_from(fields: CoordinationFields) -> Result<Self> {
1171 for (key, name) in [
1172 ("coordination.contract_file", &fields.contract_file),
1173 ("coordination.lock_file", &fields.lock_file),
1174 ] {
1175 if name.trim().is_empty()
1176 || name != name.trim()
1177 || name == "."
1178 || name.contains("..")
1179 || name.contains(['/', '\\', ':', '\0'])
1180 {
1181 bail!(
1182 "{key} must be a plain file name inside the Git common directory (no separators or '..')"
1183 );
1184 }
1185 }
1186 let token = &fields.contract_token;
1187 if token.is_empty() || token.trim() != token || token.chars().any(char::is_control) {
1188 bail!(
1189 "coordination.contract_token must be a nonempty single-line token without surrounding whitespace"
1190 );
1191 }
1192 Ok(Self {
1193 contract_file: fields.contract_file,
1194 contract_token: fields.contract_token,
1195 lock_file: fields.lock_file,
1196 })
1197 }
1198}
1199
1200#[cfg(test)]
1201pub(crate) fn test_coordination() -> Option<Coordination> {
1202 Some(Coordination {
1203 contract_file: "updater.contract".into(),
1204 contract_token: "test-protocol-v1".into(),
1205 lock_file: "updater.lock".into(),
1206 })
1207}
1208
1209#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1211#[serde(deny_unknown_fields, default)]
1212pub struct Config {
1213 pub coordination: Option<Coordination>,
1215 pub agents: Vec<AgentSpec>,
1217 pub roles: Roles,
1219 pub graph: Graph,
1221 pub blind: Blind,
1223 pub verify: Verify,
1225 pub worktree: Worktree,
1227 pub disk: Disk,
1229 pub merge: Merge,
1231 pub update: Update,
1233 pub prompts: Prompts,
1235 pub notify: Notify,
1237 pub repos: Repos,
1240 pub talk: Talk,
1242 pub daemon: Daemon,
1244 pub release: Release,
1246 pub context_windows: BTreeMap<String, u64>,
1249}
1250
1251const BUILTIN_CONTEXT_WINDOWS: &[(&str, u64)] = &[
1261 ("claude-opus-4", 200_000),
1262 ("claude-sonnet-4", 200_000),
1263 ("claude-haiku-4", 200_000),
1264 ("claude-3", 200_000),
1265 ("opus", 200_000),
1266 ("sonnet", 200_000),
1267 ("haiku", 200_000),
1268 ("gpt-5", 400_000),
1269 ("gpt-4.1", 1_000_000),
1270 ("gpt-4o", 128_000),
1271 ("o3", 200_000),
1272 ("o4-mini", 200_000),
1273 ("gemini-2.5", 1_000_000),
1274 ("deepseek", 128_000),
1275];
1276
1277impl Config {
1278 pub fn context_window(&self, model: &str) -> Option<u64> {
1283 fn lookup<'a>(model: &str, entries: impl Iterator<Item = (&'a str, u64)>) -> Option<u64> {
1284 let mut best: Option<(usize, u64)> = None;
1285 for (key, window) in entries {
1286 if key == model {
1287 return Some(window);
1288 }
1289 if model.starts_with(key) && best.is_none_or(|(len, _)| key.len() > len) {
1290 best = Some((key.len(), window));
1291 }
1292 }
1293 best.map(|(_, w)| w)
1294 }
1295 lookup(
1296 model,
1297 self.context_windows.iter().map(|(k, w)| (k.as_str(), *w)),
1298 )
1299 .or_else(|| lookup(model, BUILTIN_CONTEXT_WINDOWS.iter().copied()))
1300 }
1301}
1302
1303#[derive(Debug, Clone, Deserialize, Serialize)]
1313#[serde(deny_unknown_fields, default)]
1314pub struct Daemon {
1315 pub max_concurrent_runs: usize,
1336 pub pause_for_interrupts: bool,
1352 pub max_deputies: usize,
1359 pub release_stall_minutes: u64,
1366}
1367
1368impl Default for Daemon {
1369 fn default() -> Self {
1370 Self {
1371 max_concurrent_runs: 1,
1372 pause_for_interrupts: false,
1373 max_deputies: 2,
1374 release_stall_minutes: 60,
1375 }
1376 }
1377}
1378
1379#[derive(Debug, Clone, Deserialize, Serialize)]
1391#[serde(deny_unknown_fields, default)]
1392pub struct Repos {
1393 pub roots: Vec<PathBuf>,
1397 pub scan_ttl: u64,
1404 pub fetch_interval: u64,
1409}
1410
1411impl Default for Repos {
1412 fn default() -> Self {
1413 Self {
1414 roots: Vec::new(),
1415 scan_ttl: 86_400,
1416 fetch_interval: 600,
1417 }
1418 }
1419}
1420
1421#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1437#[serde(deny_unknown_fields, default)]
1438pub struct Prompts {
1439 pub all: String,
1441 pub implement: String,
1443 pub judge: String,
1445 pub review: String,
1447 pub fix: String,
1449}
1450
1451impl Prompts {
1452 pub fn overlay(&self, node: &str) -> Option<String> {
1457 let specific = match node {
1458 "implement" => &self.implement,
1459 "judge" | "vote" | "deliberate" => &self.judge,
1460 "review" => &self.review,
1461 "fix" => &self.fix,
1462 _ => "",
1463 };
1464 let mut parts: Vec<&str> = Vec::new();
1465 for p in [self.all.trim(), specific.trim()] {
1466 if !p.is_empty() {
1467 parts.push(p);
1468 }
1469 }
1470 if parts.is_empty() {
1471 return None;
1472 }
1473 Some(parts.join("\n\n"))
1474 }
1475}
1476
1477#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1484#[serde(deny_unknown_fields, default)]
1485pub struct Notify {
1486 pub command: Vec<String>,
1489}
1490
1491#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1493#[serde(deny_unknown_fields, default)]
1494pub struct Talk {
1495 pub allow_write: bool,
1504 pub personas: Vec<PersonaSpec>,
1509 pub operator_name: Option<String>,
1513}
1514
1515pub const OPERATOR_NAME_MAX: usize = 64;
1517
1518impl Talk {
1519 pub fn operator_name(&self) -> Option<&str> {
1521 self.operator_name
1522 .as_deref()
1523 .map(str::trim)
1524 .filter(|n| !n.is_empty())
1525 }
1526}
1527
1528#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
1530#[serde(deny_unknown_fields)]
1531pub struct PersonaSpec {
1532 pub id: String,
1534 #[serde(default)]
1537 pub name: String,
1538 #[serde(default)]
1541 pub prompt: String,
1542 #[serde(default, skip_serializing_if = "Option::is_none")]
1546 pub icon: Option<String>,
1547}
1548
1549#[derive(Debug, Clone)]
1551pub struct ResolvedRoles {
1552 pub implementers: Vec<AgentSpec>,
1554 pub judges: Vec<AgentSpec>,
1556 pub reviewers: Vec<AgentSpec>,
1558 pub fixer: Option<Vec<AgentSpec>>,
1563 pub conductor: AgentSpec,
1565 pub implementer_roster: Vec<AgentSpec>,
1573 pub judge_roster: Vec<AgentSpec>,
1577 pub reviewer_roster: Vec<AgentSpec>,
1579}
1580
1581fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
1588 let mut out = Vec::new();
1589 for (k, v) in table {
1590 if prefix.is_empty() && k == "vars" {
1591 continue;
1592 }
1593 let path = if prefix.is_empty() {
1594 k.clone()
1595 } else {
1596 format!("{prefix}.{k}")
1597 };
1598 match v {
1599 toml::Value::Array(_) => out.push(path),
1600 toml::Value::Table(t) => out.extend(array_keys(t, &path)),
1601 _ => {}
1602 }
1603 }
1604 out
1605}
1606
1607#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1609enum ArrayMerge {
1610 Append,
1614 Replace,
1617}
1618
1619fn array_merge_policy(key: &str) -> ArrayMerge {
1658 match key {
1659 "verify.e2e" | "verify.gate" | "verify.pre_gate" | "repos.roots" => ArrayMerge::Append,
1660 _ => ArrayMerge::Replace,
1661 }
1662}
1663
1664impl Config {
1665 pub fn load(path: &Path) -> Result<Self> {
1668 Self::load_layers(&[path.to_path_buf()])
1669 }
1670
1671 fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
1681 let mut ctx = teravars::system_context();
1682 let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
1683 ctx.insert("env", &env);
1684 if let Some(last) = paths.last()
1685 && let Some(dir) = last.parent()
1686 {
1687 let dir = std::fs::read_to_string(dir.join(REPO_MARKER))
1690 .map(|s| PathBuf::from(s.trim()))
1691 .unwrap_or_else(|_| dir.to_path_buf());
1692 ctx.insert("repo", &dir.to_string_lossy());
1693 ctx.insert(
1694 "repo_name",
1695 &dir.file_name().unwrap_or_default().to_string_lossy(),
1696 );
1697 }
1698 ctx
1699 }
1700
1701 pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
1709 let mut engine = teravars::Engine::default();
1710 let ctx = Self::render_ctx(paths);
1711 if paths.len() > 1 {
1712 Self::refuse_split_arrays(paths, &mut engine, &ctx).map_err(|error| {
1713 if error.downcast_ref::<ConfigFailure>().is_some() {
1714 error
1715 } else {
1716 let message = error.to_string();
1719 error
1720 .context(ConfigFailure::layers("config-merge", paths))
1721 .context(message)
1722 }
1723 })?;
1724 }
1725 let merged = teravars::load_merged(paths, &mut engine, &ctx)
1726 .map_err(|error| {
1727 let cause = ConfigFailure::render(&error, paths);
1728 anyhow::Error::new(error).context(cause)
1729 })
1730 .with_context(|| {
1731 format!(
1732 "rendering config via teravars: {}",
1733 paths
1734 .iter()
1735 .map(|p| p.display().to_string())
1736 .collect::<Vec<_>>()
1737 .join(", ")
1738 )
1739 })?;
1740 let mut table = merged.config;
1741 Self::normalize_renamed_keys(paths, &mut engine, &ctx, &mut table)?;
1742 table.remove("vars");
1745 let detect_agents = !table.contains_key("agents");
1749 let mut cfg: Self = toml::Value::Table(table)
1750 .try_into()
1751 .context("deserializing magi config")
1752 .context(ConfigFailure::layers("config-deserialize", paths))?;
1753 crate::persona::validate(&cfg.talk.personas)?;
1754 cfg.worktree.validate()?;
1755 cfg.release.validate()?;
1756 if let Some(name) = cfg.talk.operator_name() {
1757 if name.chars().count() > OPERATOR_NAME_MAX || name.chars().any(char::is_control) {
1758 bail!(
1759 "[talk] operator_name must be one line of at most {OPERATOR_NAME_MAX} characters"
1760 );
1761 }
1762 }
1763 if detect_agents {
1764 cfg.agents = Self::autodetected().agents;
1765 }
1766 Ok(cfg)
1767 }
1768
1769 fn normalize_renamed_keys(
1777 paths: &[PathBuf],
1778 engine: &mut teravars::Engine,
1779 ctx: &teravars::Context,
1780 table: &mut toml::map::Map<String, toml::Value>,
1781 ) -> Result<()> {
1782 let both = matches!(
1783 table.get("graph"),
1784 Some(toml::Value::Table(g)) if g.contains_key("candidates") && g.contains_key("implementers")
1785 );
1786 if !both {
1787 return Ok(());
1788 }
1789 let mut winner: Option<toml::Value> = None;
1790 for path in paths {
1791 let one = teravars::load_merged([path], engine, ctx)
1792 .map_err(|error| {
1793 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
1794 anyhow::Error::new(error).context(cause)
1795 })
1796 .with_context(|| format!("rendering {}", path.display()))?;
1797 let Some(toml::Value::Table(g)) = one.config.get("graph") else {
1798 continue;
1799 };
1800 if g.contains_key("candidates") && g.contains_key("implementers") {
1801 bail!(
1802 "`[graph]` sets both `implementers` and its deprecated alias \n `candidates` in {}; keep only `implementers`.",
1803 path.display()
1804 );
1805 }
1806 if let Some(v) = g.get("implementers").or_else(|| g.get("candidates")) {
1807 winner = Some(v.clone());
1808 }
1809 }
1810 if let Some(toml::Value::Table(g)) = table.get_mut("graph") {
1811 g.remove("candidates");
1812 if let Some(v) = winner {
1813 g.insert("implementers".to_owned(), v);
1814 }
1815 }
1816 Ok(())
1817 }
1818
1819 fn refuse_split_arrays(
1843 paths: &[PathBuf],
1844 engine: &mut teravars::Engine,
1845 ctx: &teravars::Context,
1846 ) -> Result<()> {
1847 let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
1848 for path in paths {
1849 let one = teravars::load_merged([path], engine, ctx)
1850 .map_err(|error| {
1851 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
1852 anyhow::Error::new(error).context(cause)
1853 })
1854 .with_context(|| format!("rendering {}", path.display()))?;
1855 for key in array_keys(&one.config, "") {
1856 if array_merge_policy(&key) == ArrayMerge::Append {
1857 continue;
1858 }
1859 if let Some(first) = seen.get(&key) {
1860 bail!(
1861 "`{key}` is an array declared in two config layers:\n \
1862 {}\n {}\nteravars appends arrays when it merges, so \
1863 magi would run the concatenation of both - which is \
1864 not what either file says. Declare `{key}` in exactly \
1865 one of them.",
1866 first.display(),
1867 path.display()
1868 );
1869 }
1870 seen.insert(key, path.clone());
1871 }
1872 }
1873 Ok(())
1874 }
1875
1876 pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
1898 let mut engine = teravars::Engine::default();
1899 let ctx = Self::render_ctx(paths);
1900 let mut out = Vec::new();
1901 for path in paths {
1902 let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
1903 continue;
1904 };
1905 let mut cur = &one.config;
1906 let mut found = None;
1907 let parts: Vec<&str> = key.split('.').collect();
1908 for (i, part) in parts.iter().enumerate() {
1909 match cur.get(*part) {
1910 Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
1911 found = Some(a);
1912 break;
1913 }
1914 Some(toml::Value::Table(t)) => cur = t,
1915 _ => break,
1916 }
1917 }
1918 let Some(values) = found else { continue };
1919 let strings: Vec<String> = values
1920 .iter()
1921 .filter_map(|v| v.as_str().map(str::to_owned))
1922 .collect();
1923 if !strings.is_empty() {
1924 out.push((path.clone(), strings));
1925 }
1926 }
1927 out
1928 }
1929
1930 pub(crate) fn layer_tables(paths: &[PathBuf]) -> Vec<(PathBuf, Result<toml::Table>)> {
1936 let mut engine = teravars::Engine::default();
1937 let ctx = Self::render_ctx(paths);
1938 paths
1939 .iter()
1940 .map(|path| {
1941 let one = teravars::load_merged([path], &mut engine, &ctx)
1942 .map(|m| m.config)
1943 .with_context(|| format!("rendering {}", path.display()));
1944 (path.clone(), one)
1945 })
1946 .collect()
1947 }
1948
1949 pub fn describe_composed(
1959 paths: &[PathBuf],
1960 commands: &[String],
1961 key: &str,
1962 empty: &str,
1963 ) -> String {
1964 if commands.is_empty() {
1965 return empty.to_owned();
1966 }
1967 let joined = commands.join(" && ");
1968 let provenance = Self::array_provenance(paths, key);
1969 if provenance.len() <= 1 {
1970 return joined;
1971 }
1972 let mut out = joined;
1973 for (path, cmds) in &provenance {
1974 out.push_str(&format!("\n [{}] {}", path.display(), cmds.join(" && ")));
1975 }
1976 out
1977 }
1978
1979 pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
1986 #[cfg(test)]
1987 crate::web::request_cost::discovery();
1988 if let Some(p) = explicit {
1989 let paths = vec![p.to_path_buf()];
1990 return Ok((Self::load_layers(&paths)?, paths));
1991 }
1992 let paths = Self::layers_checked(repo)?;
1993 if paths.is_empty() {
1994 return Ok((Self::autodetected(), paths));
1995 }
1996 Ok((Self::load_layers(&paths)?, paths))
1997 }
1998
1999 pub async fn discover_fetched(
2002 repo: &Path,
2003 explicit: Option<&Path>,
2004 ) -> Result<(Self, Vec<PathBuf>)> {
2005 if explicit.is_none() && is_git_worktree(repo) {
2006 let (remote, cfg_base) = probe_remote_base(repo);
2010 let base = crate::git::merge_base_branch(repo, &remote, cfg_base.as_deref())
2011 .await
2012 .with_context(|| ConfigFailure {
2013 stage: "config-base",
2014 target: remote.clone(),
2015 })?;
2016 let out = crate::git::fetch(repo, &remote, &base)
2017 .await
2018 .with_context(|| format!("fetching {remote}/{base} to read magi.toml"))
2019 .with_context(|| ConfigFailure {
2020 stage: "config-fetch",
2021 target: format!("{remote}/{base}"),
2022 })?;
2023 if !out.ok() {
2024 return Err(anyhow::anyhow!(
2025 "cannot read magi.toml: `git fetch {remote} {base}` failed ({}); refusing to use the local checkout's copy, which may be stale",
2026 out.stderr.lines().next().unwrap_or("").trim()
2027 )).context(ConfigFailure { stage: "config-fetch", target: format!("{remote}/{base}") });
2028 }
2029 if cfg_base.is_none() {
2030 crate::git::ensure_remote_head(repo, &remote, &base).await;
2031 }
2032 }
2033 Self::discover(repo, explicit).map_err(|error| {
2034 if error.downcast_ref::<ConfigFailure>().is_some() {
2035 error
2036 } else {
2037 error.context(ConfigFailure {
2038 stage: "config-load",
2039 target: explicit.unwrap_or(repo).to_string_lossy().into_owned(),
2040 })
2041 }
2042 })
2043 }
2044
2045 fn layers_checked(repo: &Path) -> Result<Vec<PathBuf>> {
2047 if !is_git_worktree(repo) {
2048 return Ok(Self::layers(repo));
2049 }
2050 let mut paths: Vec<PathBuf> = Self::machine_layer()
2051 .into_iter()
2052 .filter(|p| p.is_file())
2053 .collect();
2054 paths.extend(Self::repo_layers(repo)?);
2055 Ok(paths)
2056 }
2057
2058 pub(crate) fn repo_layer_description(repo: &Path, path: &Path) -> String {
2060 let cached = path.ancestors().find(|p| p.join(REPO_MARKER).is_file());
2061 if let Some(root) = cached {
2062 let relative = path.strip_prefix(root).unwrap_or(path);
2063 let reference = resolve_remote_base(repo)
2064 .map(|(remote, base)| format!("{remote}/{base}"))
2065 .unwrap_or_else(|_| "remote base".to_owned());
2066 format!(
2067 "{} at {reference} (including its includes)",
2068 repo.join(relative).display()
2069 )
2070 } else {
2071 format!("{} (including its includes)", path.display())
2072 }
2073 }
2074
2075 pub(crate) fn repo_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2078 if !is_git_worktree(repo) {
2079 return Ok([
2080 repo.join(".magi").join("config.toml"),
2081 repo.join("magi.toml"),
2082 ]
2083 .into_iter()
2084 .filter(|p| p.is_file())
2085 .collect());
2086 }
2087 remote_layers(repo)
2088 }
2089
2090 pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
2110
2111 pub fn layers(repo: &Path) -> Vec<PathBuf> {
2116 let mut paths = Vec::new();
2117 paths.extend(Self::machine_layer());
2118 paths.push(repo.join(".magi").join("config.toml"));
2119 paths.push(repo.join("magi.toml"));
2120 paths.retain(|p| p.is_file());
2121 paths
2122 }
2123
2124 #[cfg(test)]
2131 pub(crate) fn machine_layer() -> Option<PathBuf> {
2132 std::env::var(Self::CONFIG_DIR_ENV)
2133 .ok()
2134 .filter(|dir| !dir.trim().is_empty())
2135 .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
2136 }
2137
2138 #[cfg(not(test))]
2140 pub(crate) fn machine_layer() -> Option<PathBuf> {
2141 match std::env::var(Self::CONFIG_DIR_ENV) {
2142 Ok(dir) if dir.trim().is_empty() => None,
2144 Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
2145 Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
2146 }
2147 }
2148
2149 pub fn autodetected() -> Self {
2151 let mut cfg = Self::default();
2152 for (kind, id, model) in [
2153 (AgentKind::Claude, "opus", Some("opus")),
2154 (AgentKind::Claude, "sonnet", Some("sonnet")),
2155 (AgentKind::Antigravity, "antigravity", None),
2156 (AgentKind::Opencode, "opencode", None),
2157 (AgentKind::Codex, "codex", None),
2158 (AgentKind::Omp, "omp", None),
2159 ] {
2160 if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
2161 cfg.agents.push(AgentSpec {
2162 id: id.to_owned(),
2163 kind,
2164 model: model.map(str::to_owned),
2165 command: Vec::new(),
2166 extra_args: Vec::new(),
2167 env: BTreeMap::new(),
2168 prompt_delivery: None,
2169 max_turn_secs: None,
2170 });
2171 }
2172 }
2173 cfg
2174 }
2175
2176 pub fn cache_dir(&self) -> Option<PathBuf> {
2179 self.verify.cache_dir()
2180 }
2181
2182 pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
2184 self.agents
2185 .iter()
2186 .find(|a| a.id == id)
2187 .with_context(|| format!("no agent with id `{id}` in the roster"))
2188 }
2189
2190 fn rotate(&self, ids: &[String], count: usize, offset: usize) -> Result<Vec<AgentSpec>> {
2197 let mut out = Vec::with_capacity(count);
2198 for i in 0..count {
2199 let spec = if ids.is_empty() {
2200 self.agents[(i + offset) % self.agents.len()].clone()
2201 } else {
2202 self.agent(&ids[i % ids.len()])?.clone()
2203 };
2204 out.push(spec);
2205 }
2206 Ok(out)
2207 }
2208
2209 fn full_roster(&self, ids: &[String]) -> Result<Vec<AgentSpec>> {
2216 if ids.is_empty() {
2217 Ok(self.agents.clone())
2218 } else {
2219 ids.iter().map(|id| self.agent(id).cloned()).collect()
2220 }
2221 }
2222
2223 pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
2230 if self.agents.is_empty() {
2231 bail!(
2232 "agent roster is empty: no agent CLI found on PATH and no \
2233 [[agents]] in the config. Run `magi init` to write a starter \
2234 magi.toml."
2235 );
2236 }
2237 let pinned = self
2238 .graph
2239 .selected_implementer
2240 .as_ref()
2241 .map(|id| self.agent(id).cloned())
2242 .transpose()?;
2243 Ok(ResolvedRoles {
2244 implementers: match &pinned {
2245 Some(agent) => vec![agent.clone()],
2246 None => self.rotate(&self.roles.implementers, self.graph.implementers, 0)?,
2247 },
2248 judges: self.rotate(&self.roles.judges, self.graph.judges, 1)?,
2249 reviewers: self.rotate(&self.roles.reviewers, self.graph.reviewers, 0)?,
2250 fixer: match self.roles.fixer.as_ref() {
2251 Some(choice) => Some(crate::agent::pick_chain(
2254 &self.agents,
2255 Some(choice),
2256 &|_| true,
2257 "fixer",
2258 )?),
2259 None => None,
2260 },
2261 conductor: match self.roles.conductor.as_ref().map(AgentChoice::ids) {
2266 Some(ids) if ids.len() == 1 => self.agent(ids[0])?.clone(),
2267 Some(ids) if !ids.is_empty() => ids
2270 .iter()
2271 .find_map(|id| self.agent(id).ok())
2272 .cloned()
2273 .with_context(|| {
2274 format!("[roles] conductor names no agent in the roster: {ids:?}")
2275 })?,
2276 _ => crate::agent::pick(&self.agents, None, &crate::agent::installed)
2281 .unwrap_or_else(|_| self.agents[0].clone()),
2282 },
2283 implementer_roster: match pinned {
2284 Some(agent) => vec![agent],
2285 None => self.full_roster(&self.roles.implementers)?,
2286 },
2287 judge_roster: self.full_roster(&self.roles.judges)?,
2288 reviewer_roster: self.full_roster(&self.roles.reviewers)?,
2289 })
2290 }
2291
2292 pub fn advisors(&self) -> Result<Vec<AgentSpec>> {
2314 if self.agents.is_empty() {
2315 bail!(
2316 "agent roster is empty: no agent CLI found on PATH and no \
2317 [[agents]] in the config. Run `magi init` to write a starter \
2318 magi.toml."
2319 );
2320 }
2321 if !self.roles.advisors.is_empty() {
2322 return self.rotate(&self.roles.advisors, self.graph.advisors, 0);
2323 }
2324 self.rotate(&self.roles.judges, self.graph.advisors, 1)
2325 }
2326
2327 pub fn advisor_roster(&self) -> Result<Vec<AgentSpec>> {
2331 if self.roles.advisors.is_empty() {
2332 self.full_roster(&self.roles.judges)
2333 } else {
2334 self.full_roster(&self.roles.advisors)
2335 }
2336 }
2337
2338 pub fn shell(&self) -> Vec<String> {
2340 if let Some(s) = &self.verify.shell {
2341 return s.clone();
2342 }
2343 if which("sh") {
2344 vec!["sh".to_owned(), "-c".to_owned()]
2345 } else {
2346 vec!["cmd".to_owned(), "/C".to_owned()]
2347 }
2348 }
2349
2350 pub fn starter_toml() -> String {
2352 let detected = Self::autodetected();
2353 let mut s = String::from(
2354 "# magi — blind multi-agent implementation competition.\n\
2355 # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
2356 # -> blind judging -> deliberation -> private final vote\n\
2357 # -> fold losers -> review + E2E loop -> gate -> merge.\n\
2358 #\n\
2359 # Rendered by teravars: a `[vars]` table, env\n\
2360 # and system lookups, and `include = [...]` all work. Tera\n\
2361 # braces are live everywhere in this file, but comments are\n\
2362 # stripped before rendering (teravars >= 0.2.2), so a comment\n\
2363 # may quote `{{ ... }}` freely.\n\
2364 #\n\
2365 # Layers deep-merge in increasing\n\
2366 # precedence, so the roster can live once per machine in\n\
2367 # <config_dir>/magi/config.toml and each repo only states its own\n\
2368 # gate:\n\
2369 # <config_dir>/magi/config.toml < .magi/config.toml < magi.toml\n\n\
2370 [vars]\n\
2371 # Reference it as vars.cache inside Tera braces, anywhere below.\n\
2372 # Single quotes inside the braces: teravars renders the raw file\n\
2373 # text, so TOML's own \\\" escaping never reaches Tera.\n\
2374 cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
2375 );
2376 if detected.agents.is_empty() {
2377 s.push_str(
2378 "# No agent CLI was found on PATH. Fill this in by hand.\n\
2379 # kind = claude | opencode | antigravity | codex | command\n\
2380 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
2381 );
2382 } else {
2383 for a in &detected.agents {
2384 s.push_str("[[agents]]\n");
2385 s.push_str(&format!("id = {:?}\n", a.id));
2386 s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
2387 if let Some(m) = &a.model {
2388 s.push_str(&format!("model = {m:?}\n"));
2389 }
2390 s.push('\n');
2391 }
2392 }
2393 s.push_str(
2394 "# Leave a role list empty to rotate through the roster.\n\
2395 # A non-empty list is also an ordered backup list: seats take entries from the\n\
2396 # front (see [graph] counts) and a failed or out-of-quota seat moves on to the\n\
2397 # next agent to its right, each tried once. Same for judges and reviewers.\n\
2398 # implementers = [\"opus\", \"codex\", \"sonnet\"] # with implementers = 1 below: opus sits, codex then sonnet are spares\n\
2399 [roles]\n\
2400 implementers = []\n\
2401 judges = []\n\
2402 reviewers = []\n\
2403 # conductor = \"opus\" # arranges the queue; unset picks a seat like chatter does\n\
2404 # synthesizer = \"opus\" # blends the advisors into one brief; unset picks a seat like chatter does\n\
2405 # synthesizer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\
2406 # language_judge = \"jev\" # kind = \"command\" wrapper deciding if PR text is English; unset keeps the built-in heuristics\n\
2407 # dupes_judge = \"opus\" # judges duplicate-work claims; unset inherits chatter (string or fallback chain)\n\
2408 # fixer = \"opus\" # applies review findings; unset keeps the winner's own author\n\
2409 # fixer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\n\
2410 [graph]\n\
2411 # Gate GitHub prose; secret redaction is always enabled.\n\
2412 github_text_guard = true\n\
2413 # Language of PR / issue titles, bodies and comments; non-English drops the English-only check (commits stay English).\n\
2414 github_language = \"en\"\n\
2415 implementers = 3\n\
2416 judges = 3\n\
2417 deliberate_rounds = 1\n\
2418 reviewers = 3\n\
2419 review_rounds = 6\n\
2420 # Fix rounds a failing verify.gate gets before the run is blocked (0 = none).\n\
2421 gate_fix_rounds = 1\n\
2422 # Rerun a failed required CI check once before a land fix round (flaky tests).\n\
2423 rerun_flaky_checks = true\n\
2424 # Port the strengths judges named in the losing candidates onto the\n\
2425 # winner before review (best-effort; rolled back on failure or a big diff).\n\
2426 graft_runner_up = true\n\
2427 max_parallel = 4\n\
2428 language = \"en\"\n\
2429 # One CLI conversation per seat: judges keep their own argument\n\
2430 # across deliberation, the fixer keeps its implementation context.\n\
2431 sessions = true\n\
2432 # Reviewer-seat timeout. When timeout_verify is omitted, E2E and\n\
2433 # the final gate inherit this value for compatibility.\n\
2434 timeout_review = 1200\n\
2435 # Optional independent E2E/final-gate timeout; uncomment to keep\n\
2436 # verification independent if timeout_review changes later.\n\
2437 # timeout_verify = 1200\n\
2438 # Longest a seat waits for the shared build cache before it is\n\
2439 # spawned. Never counted against an agent's own timeout; expiry\n\
2440 # holds the run (resumable) instead of failing the agent.\n\
2441 # timeout_resource_wait = 1800\n\n\
2442 # What the chat calls you (persona address and the Chat's turn label).\n\
2443 # [talk]\n\
2444 # operator_name = \"Commander\"\n\n\
2445 # Chat personas (tone only; the web Chat picks one per conversation).\n\
2446 # Built in: magi, rei, misato, ritsuko, shinji, asuka, kaworu. Entries add to\n\
2447 # them, and one with a built-in's id replaces it. `default` is the plain\n\
2448 # voice and cannot be redefined (it may only set `icon`). Declare this in one\n\
2449 # layer only. `icon` is an optional avatar, display only: an absolute or\n\
2450 # ~/ path to a png/jpg/gif/webp, or a data:image/...;base64 URI, up to\n\
2451 # 256 KiB; a missing or bad one falls back to the built-in avatar.\n\
2452 # [[talk.personas]]\n\
2453 # id = \"gendo\"\n\
2454 # name = \"Gendo Ikari\"\n\
2455 # prompt = \"Speak coldly and tersely, hands folded.\"\n\
2456 # icon = \"~/pictures/gendo.png\"\n\n\
2457 [verify]\n\
2458 # Run once per review round in the winner's worktree; failures are\n\
2459 # fed back to the fixer.\n\
2460 e2e = []\n\
2461 # Final gate. Every command must exit 0 before a merge.\n\
2462 gate = []\n\
2463 # Mechanical fixers (formatters) run in the winner's worktree just\n\
2464 # before the gate; whatever they change becomes one commit. A failing\n\
2465 # command only warns - the gate stays the arbiter. Same timeout as the\n\
2466 # gate (timeout_verify). Keep it light and idempotent.\n\
2467 # pre_gate = []\n\n\
2468 # Prepare each worktree magi creates (candidates, judges, advisors,\n\
2469 # reviewers, the operator-fix and review-takeover checkouts), in order,\n\
2470 # before any agent or verify command touches it. `copy` reads from the\n\
2471 # primary checkout and never overwrites; `optional` skips a missing\n\
2472 # source. `run` goes through the shell with the worktree as cwd and\n\
2473 # fails the seat on a non-zero exit or timeout (timeout_secs, default\n\
2474 # the verify timeout). Setup must not edit tracked files, and what it\n\
2475 # leaves untracked is kept out of magi's commits. Declare this in one\n\
2476 # layer only.\n\
2477 # [worktree]\n\
2478 # setup = [\n\
2479 # { copy = \".env.example -> .env\" },\n\
2480 # { copy = \".env.local\", optional = true },\n\
2481 # { run = \"pnpm install --frozen-lockfile\", timeout_secs = 900 },\n\
2482 # ]\n\n\
2483 [merge]\n\
2484 # none | local | pr\n\
2485 mode = \"none\"\n\
2486 # release_bump = true # Rust (Cargo.toml) repositories only; a no-op elsewhere\n\n\
2487 [update]\n\
2488 # off | notify | install — checked in the background, throttled.\n\
2489 mode = \"notify\"\n\
2490 # interval = \"24h\"\n\n\
2491 # Opt-in: magi web updates and restarts only after runs/chats finish.\n\
2492 # auto_restart = false\n\
2493 # Uses interval above; off / MAGI_NO_AUTOUPDATE disable it.\n\
2494 # Standalone magi serve cannot restart. Busy work waits indefinitely.\n\
2495 # Failed tags are skipped until process restart or a different tag.\n\
2496 # Older binaries reject auto_restart: upgrade before adding the key.\n\n\
2497 [daemon]\n\
2498 # Minutes a release-bump pull request (chore/release-v*) may sit with\n\
2499 # no new commit and no check changing state before `magi serve`\n\
2500 # notices and asks you. A failed check is rerun once on its own;\n\
2501 # still red after that escalates at once. 0 turns the watcher off.\n\
2502 # release_stall_minutes = 60\n\n\
2503 [release]\n\
2504 # actions (default) | local. \"local\" is for repositories whose GitHub\n\
2505 # Actions never run (private, no minutes): the release pull request\n\
2506 # does not wait for CI, you approve the merge in magi, and then\n\
2507 # `magi serve` pushes the vX.Y.Z tag (never over an existing one) and\n\
2508 # runs `commands` from a clean checkout of the merge commit. A\n\
2509 # failure holds the release with a notice; it is never retried blind.\n\
2510 # Needs `magi serve` running and [daemon] release_stall_minutes > 0.\n\
2511 # mode = \"actions\"\n\
2512 # Run in order; the first failure stops. They see MAGI_RELEASE_VERSION,\n\
2513 # MAGI_RELEASE_TAG, MAGI_RELEASE_COMMIT and MAGI_RELEASE_PR. Make them\n\
2514 # safe to repeat: a crash mid-command is treated as unfinished.\n\
2515 # commands = [\"cargo build --release\", \"gh release create \\\"$MAGI_RELEASE_TAG\\\" --generate-notes\"]\n\
2516 # timeout_minutes = 30\n\
2517 # Repositories whose Cargo.toml is not at the root (e.g. a Tauri app).\n\
2518 # The first entry is the version of record and must be the file the\n\
2519 # repository's auto-tag.yml reads (kind \"cargo\"); the others are\n\
2520 # rewritten to the same version. Paths are relative to the repository\n\
2521 # root. Cargo.lock beside the first entry follows; package-lock.json\n\
2522 # is not touched.\n\
2523 # version_files = [\n\
2524 # { path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n\
2525 # { path = \"package.json\", kind = \"json\" },\n\
2526 # { path = \"src-tauri/tauri.conf.json\", kind = \"json\" },\n\
2527 # ]\n",
2528 );
2529 s
2530 }
2531}
2532
2533pub fn which(program: &str) -> bool {
2535 find_program(program).is_some()
2536}
2537
2538pub fn find_program(program: &str) -> Option<PathBuf> {
2547 find_program_on(program, &std::env::var_os("PATH")?)
2548}
2549
2550pub fn find_program_on(program: &str, paths: &std::ffi::OsStr) -> Option<PathBuf> {
2553 let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".EXE;.CMD;.BAT".into());
2554 find_program_in(program, paths, cfg!(windows).then_some(pathext.as_str()))
2555}
2556
2557fn find_program_in(
2558 program: &str,
2559 paths: &std::ffi::OsStr,
2560 pathext: Option<&str>,
2561) -> Option<PathBuf> {
2562 let p = Path::new(program);
2563 if p.components().count() > 1 {
2564 return p.is_file().then(|| p.to_path_buf());
2565 }
2566 std::env::split_paths(paths).find_map(|dir| match pathext {
2567 Some(exts) => {
2568 let bare = dir.join(program);
2569 if p.extension().is_some() && bare.is_file() {
2570 return Some(bare);
2571 }
2572 exts.split(';')
2573 .filter(|e| !e.is_empty())
2574 .map(|e| dir.join(format!("{program}{}", e.to_lowercase())))
2575 .find(|c| c.is_file())
2576 }
2577 None => Some(dir.join(program)).filter(|c| c.is_file()),
2578 })
2579}
2580
2581const REPO_MARKER: &str = ".magi-repo";
2583
2584fn git_out(repo: &Path, args: &[&str]) -> Option<String> {
2585 use crate::proc::Quiet as _;
2586 #[cfg(test)]
2587 crate::web::request_cost::git();
2588 let out = std::process::Command::new("git")
2589 .args(args)
2590 .quiet()
2591 .current_dir(repo)
2592 .stdin(std::process::Stdio::null())
2593 .output()
2594 .ok()?;
2595 out.status
2596 .success()
2597 .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
2598}
2599
2600fn is_git_worktree(repo: &Path) -> bool {
2603 git_out(repo, &["rev-parse", "--git-dir"]).is_some()
2604}
2605
2606#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2609pub enum OwnerHold {
2610 LandApproval,
2612 HoldContestedMerge,
2614}
2615
2616impl OwnerHold {
2617 pub const ALL: [Self; 2] = [Self::LandApproval, Self::HoldContestedMerge];
2619
2620 pub fn key(self) -> &'static str {
2622 match self {
2623 Self::LandApproval => "land_approval",
2624 Self::HoldContestedMerge => "hold_contested_merge",
2625 }
2626 }
2627
2628 pub fn base_value(self, graph: &Graph) -> bool {
2630 match self {
2631 Self::LandApproval => graph.land_approval,
2632 Self::HoldContestedMerge => graph.hold_contested_merge,
2633 }
2634 }
2635}
2636
2637pub async fn branch_owner_holds(
2640 repo: &Path,
2641 head: &str,
2642) -> (Vec<(OwnerHold, String)>, Vec<String>) {
2643 let mut holds = Vec::new();
2644 let mut diagnostics = Vec::new();
2645 if let Err(error) =
2648 crate::git::git(repo, &["cat-file", "-e", &format!("{head}^{{commit}}")]).await
2649 {
2650 diagnostics.push(format!("cannot read reviewed commit {head}: {error:#}"));
2651 return (holds, diagnostics);
2652 }
2653 for file in ["magi.toml", ".magi/config.toml"] {
2654 let object = format!("{head}:{file}");
2655 let text = match crate::git::git(repo, &["show", &object]).await {
2656 Ok(text) => text,
2657 Err(error) => {
2658 let error = format!("{error:#}");
2660 if !error.contains("does not exist in")
2661 && !error.contains("exists on disk, but not in")
2662 {
2663 diagnostics.push(format!(
2664 "cannot read reviewed branch {file} at {head}: {error}"
2665 ));
2666 }
2667 continue;
2668 }
2669 };
2670 let value = match toml::from_str::<toml::Value>(&text) {
2671 Ok(value) => value,
2672 Err(error) => {
2673 diagnostics.push(format!(
2674 "cannot parse reviewed branch {file} at {head}: {error}"
2675 ));
2676 continue;
2677 }
2678 };
2679 if value.get("include").is_some() || text.contains("{{") || text.contains("{%") {
2680 diagnostics.push(format!("reviewed branch {file} at {head}: only literal owner holds are read; includes and templates are ignored"));
2681 }
2682 for hold in OwnerHold::ALL {
2683 if value
2684 .get("graph")
2685 .and_then(|g| g.get(hold.key()))
2686 .and_then(toml::Value::as_bool)
2687 == Some(true)
2688 {
2689 holds.push((hold, file.to_owned()));
2690 }
2691 }
2692 }
2693 (holds, diagnostics)
2694}
2695
2696#[derive(Deserialize, Default)]
2697struct ProbeMerge {
2698 base: Option<String>,
2699 remote: Option<String>,
2700}
2701
2702#[derive(Deserialize, Default)]
2703struct Probe {
2704 merge: Option<ProbeMerge>,
2705}
2706
2707fn probe_merge(path: &Path, repo: &Path) -> Option<ProbeMerge> {
2713 if !path.is_file() {
2714 return None;
2715 }
2716 let paths = [path.to_path_buf()];
2717 let mut engine = teravars::Engine::default();
2718 let mut ctx = Config::render_ctx(&paths);
2719 ctx.insert("repo", &repo.to_string_lossy());
2722 ctx.insert(
2723 "repo_name",
2724 &repo.file_name().unwrap_or_default().to_string_lossy(),
2725 );
2726 if let Ok(merged) = teravars::load_merged(&paths, &mut engine, &ctx)
2727 && let Ok(probe) = toml::Value::Table(merged.config).try_into::<Probe>()
2728 {
2729 return probe.merge;
2730 }
2731 let text = std::fs::read_to_string(path).ok()?;
2732 toml::from_str::<Probe>(&text).ok()?.merge
2733}
2734
2735fn probe_remote_base(repo: &Path) -> (String, Option<String>) {
2737 let mut remote = None;
2738 let mut base = None;
2739 let mut sources: Vec<PathBuf> = Config::machine_layer().into_iter().collect();
2740 sources.push(repo.join("magi.toml"));
2741 sources.push(repo.join(".magi").join("config.toml"));
2742 for path in sources {
2743 if let Some(m) = probe_merge(&path, repo) {
2744 remote = remote.or(m.remote.filter(|s| !s.trim().is_empty()));
2745 base = base.or(m.base.filter(|s| !s.trim().is_empty()));
2746 }
2747 }
2748 (remote.unwrap_or_else(|| "origin".to_owned()), base)
2749}
2750
2751fn resolve_remote_base(repo: &Path) -> Result<(String, String)> {
2753 let (remote, base) = probe_remote_base(repo);
2754 let base = match base {
2755 Some(b) => b,
2756 None => {
2757 let head = format!("refs/remotes/{remote}/HEAD");
2758 git_out(repo, &["symbolic-ref", "--quiet", &head])
2759 .and_then(|s| crate::git::remote_head_branch(&remote, &s))
2760 .with_context(|| {
2761 format!(
2762 "cannot tell which branch of `{remote}` holds magi.toml: \
2763 set [merge] base, or run `git remote set-head {remote} -a`"
2764 )
2765 })?
2766 }
2767 };
2768 Ok((remote, base))
2769}
2770
2771fn fnv_hex(text: &str) -> String {
2772 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
2773 for b in text.bytes() {
2774 hash ^= u64::from(b);
2775 hash = hash.wrapping_mul(0x0100_0000_01b3);
2776 }
2777 format!("{hash:016x}")
2778}
2779
2780fn declares_include(text: &str) -> bool {
2786 match toml::from_str::<toml::Table>(text) {
2787 Ok(table) => {
2788 table.contains_key("include")
2789 || table
2790 .get("teravars")
2791 .and_then(toml::Value::as_table)
2792 .is_some_and(|t| t.contains_key("include"))
2793 }
2794 Err(_) => text.contains("include"),
2795 }
2796}
2797
2798fn extract_tree(repo: &Path, sha: &str, dest: &Path) -> Result<()> {
2801 use crate::proc::Quiet as _;
2802 #[cfg(test)]
2803 crate::web::request_cost::git();
2804 let mut archive = std::process::Command::new("git")
2805 .args(["archive", "--format=tar", sha])
2806 .quiet()
2807 .current_dir(repo)
2808 .stdin(std::process::Stdio::null())
2809 .stdout(std::process::Stdio::piped())
2810 .stderr(std::process::Stdio::null())
2811 .spawn()
2812 .context("running git archive")?;
2813 let tar = std::process::Command::new("tar")
2814 .arg("-x")
2815 .arg("-C")
2816 .arg(dest)
2817 .quiet()
2818 .stdin(archive.stdout.take().context("git archive has no stdout")?)
2819 .output()
2820 .context("running tar")?;
2821 let status = archive.wait().context("waiting for git archive")?;
2822 if !status.success() || !tar.status.success() {
2823 bail!(
2824 "cannot unpack {sha} for the config's includes: {}",
2825 String::from_utf8_lossy(&tar.stderr).trim()
2826 );
2827 }
2828 Ok(())
2829}
2830
2831fn remote_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2834 let (remote, base) = resolve_remote_base(repo)?;
2835 let tracking = format!("refs/remotes/{remote}/{base}");
2836 let spec = format!("{tracking}^{{commit}}");
2837 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
2838 .map(|s| s.trim().to_owned())
2839 .filter(|s| !s.is_empty())
2840 .with_context(|| {
2841 format!(
2842 "`{remote}/{base}` does not exist in this checkout; fetch it \
2843 (`git fetch {remote} {base}`) or set [merge] base/remote. magi will not read \
2844 a possibly stale local magi.toml instead"
2845 )
2846 })?;
2847 let key = format!("{sha}-{}", fnv_hex(&repo.to_string_lossy()));
2848 let rels = [".magi/config.toml", "magi.toml"];
2849 let mut texts: Vec<(&str, String)> = Vec::new();
2850 for rel in rels {
2851 let object = format!("{sha}:{rel}");
2852 if git_out(repo, &["cat-file", "-e", &object]).is_none() {
2853 continue;
2854 }
2855 let Some(text) = git_out(repo, &["show", &object]) else {
2856 bail!("cannot read {rel} from {remote}/{base} ({sha})");
2857 };
2858 texts.push((rel, text));
2859 }
2860 let wants_tree = texts.iter().any(|(_, t)| declares_include(t));
2861 let build = |root: &Path| -> Result<PathBuf> {
2865 let final_dir = root.join(&key);
2866 if !final_dir.is_dir() {
2867 std::fs::create_dir_all(root)?;
2868 let tmp = root.join(format!(
2869 "{key}.tmp-{}-{}",
2870 std::process::id(),
2871 std::time::SystemTime::now()
2872 .duration_since(std::time::UNIX_EPOCH)
2873 .map(|d| d.as_nanos())
2874 .unwrap_or_default()
2875 ));
2876 let filled = (|| -> Result<()> {
2877 std::fs::create_dir_all(&tmp)?;
2878 if wants_tree {
2879 extract_tree(repo, &sha, &tmp)?;
2880 }
2881 for (rel, text) in &texts {
2882 let file = tmp.join(rel);
2883 let parent = file.parent().unwrap_or(&tmp);
2884 std::fs::create_dir_all(parent)?;
2885 std::fs::write(&file, text)?;
2886 std::fs::write(parent.join(REPO_MARKER), repo.to_string_lossy().as_bytes())?;
2887 }
2888 Ok(())
2889 })();
2890 if let Err(e) = filled {
2891 let _ = std::fs::remove_dir_all(&tmp);
2892 return Err(e);
2893 }
2894 if std::fs::rename(&tmp, &final_dir).is_err() {
2895 let _ = std::fs::remove_dir_all(&tmp);
2897 if !final_dir.is_dir() {
2898 bail!("cannot place {}", final_dir.display());
2899 }
2900 }
2901 }
2902 Ok(final_dir)
2903 };
2904 let common = git_out(
2905 repo,
2906 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
2907 )
2908 .map(|s| PathBuf::from(s.trim()).join("magi").join("config"));
2909 let dir = match common.map(|c| build(&c)) {
2910 Some(Ok(d)) => d,
2911 _ => build(&std::env::temp_dir().join("magi-config"))
2912 .with_context(|| format!("extracting config from {remote}/{base}"))?,
2913 };
2914 Ok(texts.iter().map(|(rel, _)| dir.join(rel)).collect())
2915}
2916
2917#[cfg(test)]
2918mod tests {
2919 #[test]
2920 fn coordination_defaults_off_and_validates_rendered_layer_values() {
2921 let dir = tempfile::tempdir().unwrap();
2922 let machine = dir.path().join("machine.toml");
2923 let repo = dir.path().join("repo.toml");
2924 std::fs::write(&machine, "").unwrap();
2925 assert!(Config::default().coordination.is_none());
2926 assert!(Config::load(&machine).unwrap().coordination.is_none());
2927 std::fs::write(
2928 &machine,
2929 r#"
2930[vars]
2931contract = "updater.contract"
2932[coordination]
2933contract_file = "{{ vars.contract }}"
2934contract_token = "protocol-v1"
2935lock_file = "updater.lock"
2936"#,
2937 )
2938 .unwrap();
2939 let cfg = Config::load(&machine).unwrap();
2940 let policy = cfg.coordination.unwrap();
2941 assert_eq!(policy.contract_file, "updater.contract");
2942 assert_eq!(policy.contract_token, "protocol-v1");
2943 assert_eq!(policy.lock_file, "updater.lock");
2944 std::fs::write(&repo, "[coordination]\nlock_file = 'repository.lock'\n").unwrap();
2945 let cfg = Config::load_layers(&[machine.clone(), repo.clone()]).unwrap();
2946 let policy = cfg.coordination.unwrap();
2947 assert_eq!(policy.contract_file, "updater.contract");
2948 assert_eq!(policy.lock_file, "repository.lock");
2949 std::fs::write(
2950 &repo,
2951 r#"
2952[vars]
2953bad = "../escape"
2954[coordination]
2955lock_file = "{{ vars.bad }}"
2956"#,
2957 )
2958 .unwrap();
2959 let error = Config::load_layers(&[machine, repo]).unwrap_err();
2960 assert!(format!("{error:#}").contains("coordination.lock_file"));
2961 }
2962
2963 #[test]
2964 fn coordination_rejects_invalid_names_tokens_and_incomplete_sections() {
2965 let dir = tempfile::tempdir().unwrap();
2966 let path = dir.path().join("config.toml");
2967 let valid = toml::toml! {
2968 [coordination]
2969 contract_file = "updater.contract"
2970 contract_token = "protocol-v1"
2971 lock_file = "updater.lock"
2972 };
2973 for key in ["contract_file", "lock_file"] {
2974 for bad in [
2975 "",
2976 " ",
2977 " file",
2978 "file ",
2979 "\tfile",
2980 "file\t",
2981 ".",
2982 "..",
2983 "file..name",
2984 "../escape",
2985 "a/b",
2986 "a\\b",
2987 "/absolute",
2988 "C:drive",
2989 "C:\\absolute",
2990 "nul\0name",
2991 ] {
2992 let mut table = valid.clone();
2993 table["coordination"][key] = bad.into();
2994 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
2995 let error = Config::load(&path).unwrap_err();
2996 assert!(
2997 format!("{error:#}").contains(&format!("coordination.{key}")),
2998 "{bad:?}: {error:#}"
2999 );
3000 }
3001 }
3002 for bad in ["", " ", " token", "token ", "two\nlines", "two\rlines"] {
3003 let mut table = valid.clone();
3004 table["coordination"]["contract_token"] = bad.into();
3005 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3006 let error = Config::load(&path).unwrap_err();
3007 assert!(
3008 format!("{error:#}").contains("coordination.contract_token"),
3009 "{error:#}"
3010 );
3011 }
3012 for key in ["contract_file", "contract_token", "lock_file"] {
3013 let mut table = valid.clone();
3014 table["coordination"].as_table_mut().unwrap().remove(key);
3015 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3016 let error = Config::load(&path).unwrap_err();
3017 assert!(
3018 format!("{error:#}").contains(&format!("coordination.{key}")),
3019 "{error:#}"
3020 );
3021 }
3022 let mut table = valid;
3023 table["coordination"]
3024 .as_table_mut()
3025 .unwrap()
3026 .insert("typo".into(), "value".into());
3027 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3028 assert!(format!("{:#}", Config::load(&path).unwrap_err()).contains("typo"));
3029 }
3030
3031 #[test]
3032 fn context_window_prefers_exact_then_longest_prefix_and_user_over_builtin() {
3033 let mut cfg = Config::default();
3034 assert_eq!(
3035 cfg.context_window("claude-sonnet-4-5-20250929"),
3036 Some(200_000)
3037 );
3038 assert_eq!(cfg.context_window("gpt-4.1-mini"), Some(1_000_000));
3039 assert_eq!(cfg.context_window("mystery-model"), None);
3040 cfg.context_windows
3041 .insert("claude-sonnet-4-5".into(), 1_000_000);
3042 cfg.context_windows.insert("claude-sonnet-4".into(), 5);
3043 cfg.context_windows.insert("mystery".into(), 32_768);
3044 assert_eq!(
3046 cfg.context_window("claude-sonnet-4-5-20250929"),
3047 Some(1_000_000)
3048 );
3049 cfg.context_windows
3051 .insert("claude-sonnet-4-5-20250929".into(), 7);
3052 assert_eq!(cfg.context_window("claude-sonnet-4-5-20250929"), Some(7));
3053 assert_eq!(cfg.context_window("mystery-model"), Some(32_768));
3054 }
3055
3056 use super::*;
3057
3058 #[test]
3061 fn windows_lookup_picks_the_cmd_shim_over_the_extensionless_script() {
3062 let dir = tempfile::tempdir().unwrap();
3063 std::fs::write(dir.path().join("codex"), "#!/bin/sh\n").unwrap();
3064 std::fs::write(dir.path().join("codex.cmd"), "@echo off\n").unwrap();
3065 let paths = dir.path().as_os_str();
3066 assert_eq!(
3067 find_program_in("codex", paths, Some(".EXE;.CMD")),
3068 Some(dir.path().join("codex.cmd"))
3069 );
3070 assert_eq!(
3071 find_program_in("codex", paths, None),
3072 Some(dir.path().join("codex"))
3073 );
3074 assert_eq!(find_program_in("claude", paths, Some(".EXE;.CMD")), None);
3075 }
3076
3077 fn spec(id: &str) -> AgentSpec {
3078 AgentSpec {
3079 id: id.to_owned(),
3080 kind: AgentKind::Command,
3081 model: None,
3082 command: vec!["true".to_owned()],
3083 extra_args: Vec::new(),
3084 env: BTreeMap::new(),
3085 prompt_delivery: None,
3086 max_turn_secs: None,
3087 }
3088 }
3089
3090 #[test]
3091 fn github_text_guard_defaults_on_and_can_be_disabled() {
3092 let default: Graph = toml::from_str("").unwrap();
3093 assert!(default.github_text_guard);
3094 let disabled: Graph = toml::from_str("github_text_guard = false").unwrap();
3095 assert!(!disabled.github_text_guard);
3096 let config = layered("", "[graph]\ngithub_text_guard = false\n").unwrap();
3097 assert!(!config.graph.github_text_guard);
3098 assert!(Config::starter_toml().contains("github_text_guard = true"));
3099 }
3100
3101 #[test]
3102 fn rerun_flaky_checks_defaults_on_and_is_in_the_starter() {
3103 assert!(Graph::default().rerun_flaky_checks);
3104 let off: Graph = toml::from_str("rerun_flaky_checks = false").unwrap();
3105 assert!(!off.rerun_flaky_checks);
3106 assert!(Config::starter_toml().contains("rerun_flaky_checks = true"));
3107 }
3108
3109 #[test]
3110 fn timeout_verify_omitted_from_old_toml_inherits_timeout_review() {
3111 let g: Graph = toml::from_str("timeout_review = 3600").expect("parse");
3116 assert_eq!(g.timeout_verify, None);
3117 assert_eq!(g.verify_timeout(), 3600);
3118 }
3119
3120 #[test]
3121 fn shrinking_timeout_review_does_not_shrink_timeout_verify() {
3122 let g: Graph = toml::from_str("timeout_review = 45").expect("parse");
3127 assert_eq!(g.timeout_review, 45);
3128 assert_eq!(
3129 g.verify_timeout(),
3130 45,
3131 "an omitted legacy value follows review"
3132 );
3133 let explicit: Graph = toml::from_str("timeout_review = 45\ntimeout_verify = 1200")
3134 .expect("parse explicit override");
3135 assert_eq!(explicit.verify_timeout(), 1200);
3136 }
3137
3138 #[test]
3139 fn graph_implementers_new_key_loads_and_old_key_is_an_alias() {
3140 let g: Graph = toml::from_str("implementers = 4\n").unwrap();
3141 assert_eq!(g.implementers, 4);
3142 let g: Graph = toml::from_str("candidates = 5\n").unwrap();
3143 assert_eq!(g.implementers, 5);
3144 }
3145
3146 fn layered(lower: &str, upper: &str) -> Result<Config> {
3147 let dir = tempfile::tempdir().unwrap();
3148 let a = dir.path().join("a.toml");
3149 let b = dir.path().join("b.toml");
3150 std::fs::write(&a, lower).unwrap();
3151 std::fs::write(&b, upper).unwrap();
3152 Config::load_layers(&[a, b])
3153 }
3154
3155 #[test]
3156 fn graph_implementers_higher_layer_wins_across_spellings() {
3157 let c = layered("[graph]\ncandidates = 2\n", "[graph]\nimplementers = 5\n").unwrap();
3158 assert_eq!(c.graph.implementers, 5);
3159 let c = layered("[graph]\nimplementers = 2\n", "[graph]\ncandidates = 5\n").unwrap();
3160 assert_eq!(c.graph.implementers, 5);
3161 let c = layered("[graph]\ncandidates = 2\n", "[graph]\njudges = 3\n").unwrap();
3162 assert_eq!(c.graph.implementers, 2);
3163 }
3164
3165 #[test]
3166 fn graph_implementers_both_keys_in_one_layer_is_refused() {
3167 let err = layered("", "[graph]\ncandidates = 2\nimplementers = 3\n")
3168 .unwrap_err()
3169 .to_string();
3170 assert!(
3171 err.contains("candidates") && err.contains("implementers"),
3172 "{err}"
3173 );
3174 assert!(err.contains("b.toml"), "{err}");
3175 }
3176
3177 #[test]
3178 fn a_toml_layer_written_before_these_fields_existed_still_parses() {
3179 let g: Graph =
3183 toml::from_str("candidates = 1\nreviewers = 3\nreview_rounds = 6\nmax_parallel = 4\n")
3184 .expect("an old-shaped [graph] table must still parse");
3185 assert_eq!(g.verify_timeout(), Graph::default().timeout_review);
3186 assert!(
3187 !g.e2e_every_round,
3188 "off by default, same as before this field existed"
3189 );
3190 }
3191
3192 #[test]
3193 fn empty_roles_rotate_judges_off_their_own_candidate() {
3194 let cfg = Config {
3197 agents: vec![spec("a"), spec("b"), spec("c")],
3198 graph: Graph {
3199 implementers: 3,
3200 ..Graph::default()
3201 },
3202 ..Config::default()
3203 };
3204 let roles = cfg.resolve_roles().unwrap();
3205 let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
3206 let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
3207 assert_eq!(impls, ["a", "b", "c"]);
3208 assert_eq!(judges, ["b", "c", "a"]);
3209 for (i, j) in judges.iter().enumerate() {
3210 assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
3211 }
3212 }
3213
3214 #[test]
3215 fn single_agent_roster_fills_every_seat() {
3216 let cfg = Config {
3217 agents: vec![spec("solo")],
3218 graph: Graph {
3219 implementers: 3,
3220 ..Graph::default()
3221 },
3222 ..Config::default()
3223 };
3224 let roles = cfg.resolve_roles().unwrap();
3225 assert_eq!(roles.implementers.len(), 3);
3226 assert!(roles.judges.iter().all(|a| a.id == "solo"));
3227 }
3228
3229 #[test]
3230 fn implementer_roster_is_the_whole_agent_list_untruncated_when_unset() {
3231 let cfg = Config {
3236 agents: vec![spec("a"), spec("b"), spec("c")],
3237 graph: Graph {
3238 implementers: 1,
3239 ..Graph::default()
3240 },
3241 ..Config::default()
3242 };
3243 let roles = cfg.resolve_roles().unwrap();
3244 assert_eq!(roles.implementers.len(), 1);
3245 let roster: Vec<&str> = roles
3246 .implementer_roster
3247 .iter()
3248 .map(|a| a.id.as_str())
3249 .collect();
3250 assert_eq!(roster, ["a", "b", "c"]);
3251 }
3252
3253 #[test]
3254 fn implementer_roster_follows_explicit_ids_in_the_order_named() {
3255 let cfg = Config {
3256 agents: vec![spec("a"), spec("b"), spec("c")],
3257 roles: Roles {
3258 implementers: vec!["c".to_owned(), "a".to_owned()],
3259 ..Roles::default()
3260 },
3261 graph: Graph {
3262 implementers: 1,
3263 ..Graph::default()
3264 },
3265 ..Config::default()
3266 };
3267 let roles = cfg.resolve_roles().unwrap();
3268 assert_eq!(roles.implementers.len(), 1);
3270 assert_eq!(roles.implementers[0].id, "c");
3271 let roster: Vec<&str> = roles
3272 .implementer_roster
3273 .iter()
3274 .map(|a| a.id.as_str())
3275 .collect();
3276 assert_eq!(roster, ["c", "a"]);
3277 }
3278
3279 #[test]
3280 fn explicit_roles_win() {
3281 let cfg = Config {
3282 agents: vec![spec("a"), spec("b")],
3283 roles: Roles {
3284 implementers: vec!["b".to_owned()],
3285 judges: vec!["a".to_owned()],
3286 reviewers: Vec::new(),
3287 fixer: Some("a".into()),
3288 ..Roles::default()
3289 },
3290 ..Config::default()
3291 };
3292 let roles = cfg.resolve_roles().unwrap();
3293 assert!(roles.implementers.iter().all(|a| a.id == "b"));
3294 assert!(roles.judges.iter().all(|a| a.id == "a"));
3295 let fixer = roles.fixer.unwrap();
3296 assert_eq!(fixer.len(), 1);
3297 assert_eq!(fixer[0].id, "a");
3298 assert_eq!(roles.conductor.id, "a");
3299 }
3300
3301 #[test]
3302 fn fixer_takes_a_string_or_an_ordered_chain() {
3303 let one: Roles = toml::from_str("fixer = \"a\"").unwrap();
3304 assert_eq!(one.fixer.as_ref().unwrap().ids(), ["a"]);
3305 let chain: Roles = toml::from_str("fixer = [\"b\", \"a\"]").unwrap();
3306 assert_eq!(chain.fixer.as_ref().unwrap().ids(), ["b", "a"]);
3307
3308 let resolve = |fixer: Option<AgentChoice>| {
3309 Config {
3310 agents: vec![spec("a"), spec("b"), spec("c")],
3311 roles: Roles {
3312 fixer,
3313 ..Roles::default()
3314 },
3315 ..Config::default()
3316 }
3317 .resolve_roles()
3318 };
3319 let ids = |r: &ResolvedRoles| -> Vec<String> {
3320 r.fixer
3321 .as_ref()
3322 .unwrap()
3323 .iter()
3324 .map(|s| s.id.clone())
3325 .collect()
3326 };
3327 assert_eq!(ids(&resolve(Some("c".into())).unwrap()), ["c"]);
3329 assert!(resolve(None).unwrap().fixer.is_none());
3330 let chain = AgentChoice::Chain(vec!["b".into(), "zzz".into(), "a".into(), "b".into()]);
3332 assert_eq!(ids(&resolve(Some(chain)).unwrap()), ["b", "a"]);
3333 let err = resolve(Some(AgentChoice::Chain(vec!["zzz".into()]))).unwrap_err();
3335 assert!(format!("{err:#}").contains("fixer"), "{err:#}");
3336 }
3337
3338 #[test]
3339 fn unknown_agent_id_is_an_error() {
3340 let cfg = Config {
3341 agents: vec![spec("a")],
3342 roles: Roles {
3343 judges: vec!["nope".to_owned()],
3344 ..Roles::default()
3345 },
3346 ..Config::default()
3347 };
3348 assert!(cfg.resolve_roles().is_err());
3349 }
3350
3351 #[test]
3352 fn conductor_role_is_resolved_validated_and_has_a_fallback() {
3353 let mut cfg = Config {
3354 agents: vec![spec("a"), spec("b")],
3355 ..Config::default()
3356 };
3357 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "a");
3358
3359 cfg.roles.conductor = Some("b".into());
3360 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "b");
3361
3362 cfg.roles.conductor = Some("missing".into());
3363 assert!(cfg.resolve_roles().is_err());
3364 }
3365
3366 #[test]
3367 fn a_standalone_role_takes_a_string_or_an_array_and_round_trips() {
3368 let one: Roles = toml::from_str("synthesizer = \"opus\"").unwrap();
3369 assert_eq!(one.synthesizer, Some(AgentChoice::One("opus".to_owned())));
3370 assert_eq!(primary(one.synthesizer.as_ref()), Some("opus"));
3371
3372 let chain: Roles = toml::from_str("chatter = [\"opus\", \"codex\"]").unwrap();
3373 assert_eq!(chain.chatter.as_ref().unwrap().ids(), ["opus", "codex"]);
3374 assert_eq!(primary(chain.chatter.as_ref()), Some("opus"));
3375
3376 for roles in [one, chain] {
3377 let text = toml::to_string(&roles).unwrap();
3378 let back: Roles = toml::from_str(&text).unwrap();
3379 assert_eq!(back.synthesizer, roles.synthesizer);
3380 assert_eq!(back.chatter, roles.chatter);
3381 }
3382 let text = toml::to_string(&Roles {
3383 conductor: Some("x".into()),
3384 ..Roles::default()
3385 })
3386 .unwrap();
3387 assert!(
3388 text.contains("conductor = \"x\""),
3389 "string stays a string: {text}"
3390 );
3391 assert!(toml::from_str::<Roles>("synthesizer = 3").is_err());
3392 }
3393
3394 #[test]
3395 fn dupes_judge_role_accepts_strings_and_chains_and_round_trips() {
3396 for (text, ids) in [
3397 (r#"dupes_judge = "dedicated""#, vec!["dedicated"]),
3398 (
3399 r#"dupes_judge = ["first", "second"]"#,
3400 vec!["first", "second"],
3401 ),
3402 ("dupes_judge = []", vec![]),
3403 ] {
3404 let roles: Roles = toml::from_str(text).unwrap();
3405 assert_eq!(roles.dupes_judge.as_ref().unwrap().ids(), ids);
3406 let serialized = toml::to_string(&roles).unwrap();
3407 let back: Roles = toml::from_str(&serialized).unwrap();
3408 assert_eq!(back.dupes_judge, roles.dupes_judge);
3409 assert!(serialized.contains(text));
3410 }
3411 assert!(toml::from_str::<Roles>("dupes_judge = 3").is_err());
3412 assert!(Roles::default().dupes_judge.is_none());
3413 assert!(Config::starter_toml().contains("# dupes_judge ="));
3414
3415 let mut cfg = Config {
3417 agents: vec![spec("a")],
3418 ..Config::default()
3419 };
3420 cfg.roles.dupes_judge = Some("missing".into());
3421 assert!(cfg.resolve_roles().is_ok());
3422 }
3423
3424 #[test]
3425 fn an_empty_choice_counts_as_unset() {
3426 assert!(AgentChoice::Chain(Vec::new()).ids().is_empty());
3427 assert!(AgentChoice::One(" ".to_owned()).ids().is_empty());
3428 assert_eq!(primary(Some(&AgentChoice::Chain(vec![]))), None);
3429 }
3430
3431 #[test]
3432 fn synthesizer_role_is_a_lazy_lookup_with_the_same_fallback_as_chatter() {
3433 let mut cfg = Config {
3439 agents: vec![spec("a"), spec("b")],
3440 ..Config::default()
3441 };
3442 let want = primary(cfg.roles.synthesizer.as_ref());
3443 assert_eq!(
3444 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
3445 .unwrap()
3446 .id,
3447 "a",
3448 "unset falls back to agent::pick's own default order"
3449 );
3450
3451 cfg.roles.synthesizer = Some("b".into());
3452 let want = primary(cfg.roles.synthesizer.as_ref());
3453 assert_eq!(
3454 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
3455 .unwrap()
3456 .id,
3457 "b",
3458 "the named agent wins over the default order"
3459 );
3460 }
3461
3462 #[test]
3463 fn empty_roster_is_an_error() {
3464 assert!(Config::default().resolve_roles().is_err());
3465 }
3466
3467 #[test]
3468 fn advise_defaults_to_on_with_three_proposals() {
3469 let g = Graph::default();
3470 assert!(g.advise);
3471 assert!(g.graft_runner_up, "graft is on by default");
3472 assert_eq!(g.advisors, 3);
3473 }
3474
3475 #[test]
3476 fn unset_advisors_falls_back_to_the_judge_roster() {
3477 let cfg = Config {
3478 agents: vec![spec("a"), spec("b")],
3479 roles: Roles {
3480 judges: vec!["b".to_owned()],
3481 ..Roles::default()
3482 },
3483 graph: Graph {
3484 advisors: 2,
3485 ..Graph::default()
3486 },
3487 ..Config::default()
3488 };
3489 let advisors = cfg.advisors().expect("advisors resolve");
3490 assert_eq!(advisors.len(), 2);
3491 assert!(
3492 advisors.iter().all(|a| a.id == "b"),
3493 "an unset [roles] advisors must fall back to [roles] judges: {advisors:?}"
3494 );
3495 }
3496
3497 #[test]
3498 fn an_explicit_advisor_roster_wins_over_the_judge_fallback() {
3499 let cfg = Config {
3500 agents: vec![spec("a"), spec("b")],
3501 roles: Roles {
3502 judges: vec!["b".to_owned()],
3503 advisors: vec!["a".to_owned()],
3504 ..Roles::default()
3505 },
3506 graph: Graph {
3507 advisors: 2,
3508 ..Graph::default()
3509 },
3510 ..Config::default()
3511 };
3512 let advisors = cfg.advisors().expect("advisors resolve");
3513 assert!(advisors.iter().all(|a| a.id == "a"));
3514 }
3515
3516 #[test]
3522 fn an_unconfigured_advisor_and_judge_roster_resolve_to_the_same_agents() {
3523 let cfg = Config {
3524 agents: vec![spec("a"), spec("b"), spec("c")],
3525 graph: Graph {
3526 advisors: 3,
3527 judges: 3,
3528 ..Graph::default()
3529 },
3530 ..Config::default()
3531 };
3532 let advisors = cfg.advisors().expect("advisors resolve");
3533 let judges = cfg.resolve_roles().expect("roles resolve").judges;
3534 let advisor_ids: Vec<&str> = advisors.iter().map(|a| a.id.as_str()).collect();
3535 let judge_ids: Vec<&str> = judges.iter().map(|a| a.id.as_str()).collect();
3536 assert_eq!(
3537 advisor_ids, judge_ids,
3538 "an unconfigured advisor roster must be the same seats an unconfigured judge panel gets"
3539 );
3540 }
3541
3542 #[test]
3543 fn an_unresolvable_advisor_seat_is_an_error_naming_the_id() {
3544 let cfg = Config {
3545 agents: vec![spec("a")],
3546 roles: Roles {
3547 advisors: vec!["nope".to_owned()],
3548 ..Roles::default()
3549 },
3550 graph: Graph {
3551 advisors: 1,
3552 ..Graph::default()
3553 },
3554 ..Config::default()
3555 };
3556 let err = cfg.advisors().expect_err("`nope` is not in the roster");
3557 assert!(format!("{err:#}").contains("nope"));
3558 }
3559
3560 #[test]
3561 fn repos_default_to_no_roots_and_a_day_of_trust() {
3562 assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
3563 assert_eq!(Config::default().repos.scan_ttl, 86_400);
3564 assert_eq!(Config::default().repos.fetch_interval, 600);
3565 }
3566
3567 #[test]
3568 fn a_config_file_with_no_repos_table_still_loads() {
3569 let dir = tempfile::tempdir().unwrap();
3570 let path = dir.path().join("magi.toml");
3571 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
3572 let cfg = Config::load(&path).expect("must load without [repos]");
3573 assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
3574 assert_eq!(cfg.repos.scan_ttl, 86_400);
3575 }
3576
3577 #[test]
3592 fn a_test_build_does_not_read_the_operators_machine_config() {
3593 let repo = tempfile::tempdir().unwrap();
3594 std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
3595
3596 let layers = Config::layers(repo.path());
3597 assert_eq!(
3598 layers,
3599 vec![repo.path().join("magi.toml")],
3600 "only the fixture's own file may be a layer"
3601 );
3602 if let Some(real) = dirs::config_dir() {
3603 let machine = real.join("magi").join("config.toml");
3604 assert!(
3605 !layers.contains(&machine),
3606 "the operator's {} must not be a layer in a test build",
3607 machine.display()
3608 );
3609 }
3610 }
3611
3612 #[test]
3613 fn auto_upgrade_config_defaults_and_opt_in() {
3614 let default: Update = toml::from_str("").unwrap();
3615 assert!(!default.auto_restart);
3616 assert_eq!(default.mode, UpdateMode::Notify);
3617 let enabled: Update = toml::from_str("auto_restart = true\ninterval = \"2h\"\n").unwrap();
3618 assert!(enabled.auto_restart);
3619 assert_eq!(enabled.interval.as_deref(), Some("2h"));
3620 assert!(toml::from_str::<Update>("auto_restart = \"yes\"").is_err());
3621 }
3622
3623 #[test]
3624 fn starter_toml_loads_through_teravars() {
3625 let dir = tempfile::tempdir().unwrap();
3626 let path = dir.path().join("magi.toml");
3627 std::fs::write(&path, Config::starter_toml()).unwrap();
3628 let parsed = Config::load(&path).expect("starter config must load");
3629 assert_eq!(parsed.graph.implementers, 3);
3630 assert_eq!(parsed.merge.mode, MergeMode::None);
3631 assert_eq!(parsed.merge.style, MergeStyle::Merge);
3632 assert!(parsed.graph.sessions);
3633 assert!(parsed.graph.github_text_guard);
3634 assert_eq!(parsed.graph.timeout_review, 1200);
3635 assert_eq!(parsed.graph.verify_timeout(), 1200);
3636 assert_eq!(parsed.update.mode, UpdateMode::Notify);
3637 }
3638
3639 #[test]
3640 fn release_defaults_to_actions_and_the_starter_documents_it() {
3641 let dir = tempfile::tempdir().unwrap();
3642 let path = dir.path().join("magi.toml");
3643 std::fs::write(&path, Config::starter_toml()).unwrap();
3644 let r = Config::load(&path).unwrap().release;
3645 assert_eq!(r.mode, ReleaseMode::Actions);
3646 assert!(!r.is_local());
3647 assert!(r.commands.is_empty());
3648 assert_eq!(r.timeout_minutes, 30);
3649 assert!(Config::starter_toml().contains("# mode = \"actions\""));
3650 }
3651
3652 #[test]
3653 fn release_local_parses_and_unknown_keys_are_refused() {
3654 let dir = tempfile::tempdir().unwrap();
3655 let path = dir.path().join("magi.toml");
3656 std::fs::write(
3657 &path,
3658 "[release]\nmode = \"local\"\ncommands = [\"true\", \"echo $MAGI_RELEASE_TAG\"]\ntimeout_minutes = 5\n",
3659 )
3660 .unwrap();
3661 let r = Config::load(&path).unwrap().release;
3662 assert!(r.is_local());
3663 assert_eq!(r.commands.len(), 2);
3664 assert_eq!(r.timeout_minutes, 5);
3665 std::fs::write(&path, "[release]\nmode = \"local\"\nbogus = 1\n").unwrap();
3666 assert!(Config::load(&path).is_err());
3667 std::fs::write(&path, "[release]\nmode = \"gha\"\n").unwrap();
3668 assert!(Config::load(&path).is_err());
3669 }
3670
3671 #[test]
3672 fn pre_gate_defaults_to_empty_and_the_starter_documents_it() {
3673 let dir = tempfile::tempdir().unwrap();
3674 let path = dir.path().join("magi.toml");
3675 std::fs::write(&path, Config::starter_toml()).unwrap();
3676 assert!(Config::load(&path).unwrap().verify.pre_gate.is_empty());
3677 assert!(Config::starter_toml().contains("# pre_gate = []"));
3678 }
3679
3680 #[test]
3681 fn release_version_files_parse_default_empty_and_are_validated() {
3682 let dir = tempfile::tempdir().unwrap();
3683 let path = dir.path().join("magi.toml");
3684 std::fs::write(&path, "").unwrap();
3685 assert!(
3686 Config::load(&path)
3687 .unwrap()
3688 .release
3689 .version_files
3690 .is_empty()
3691 );
3692 std::fs::write(
3693 &path,
3694 "[release]\nversion_files = [\n{ path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n{ path = \"package.json\", kind = \"json\" },\n]\n",
3695 )
3696 .unwrap();
3697 let files = Config::load(&path).unwrap().release.version_files;
3698 assert_eq!(files.len(), 2);
3699 assert_eq!(files[1].kind, VersionKind::Json);
3700 for bad in [
3701 "{ path = \"package.json\", kind = \"json\" }",
3702 "{ path = \"../Cargo.toml\", kind = \"cargo\" }",
3703 "{ path = \"Cargo.toml\", kind = \"cargo\", extra = 1 }",
3704 "{ path = \"Cargo.toml\", kind = \"yaml\" }",
3705 ] {
3706 std::fs::write(&path, format!("[release]\nversion_files = [{bad}]\n")).unwrap();
3707 assert!(Config::load(&path).is_err(), "{bad}");
3708 }
3709 assert!(Config::starter_toml().contains("# version_files = ["));
3710 }
3711
3712 #[test]
3713 fn starter_toml_explains_inherited_and_explicit_verify_timeouts() {
3714 let starter = Config::starter_toml();
3715 assert!(starter.contains("When timeout_verify is omitted, E2E and"));
3716 assert!(starter.contains("verification independent if timeout_review changes later"));
3717 assert!(starter.contains("# timeout_verify = 1200"));
3718 }
3719
3720 #[test]
3721 fn starter_toml_documents_chat_personas() {
3722 let starter = Config::starter_toml();
3723 assert!(starter.contains("# [[talk.personas]]"));
3724 assert!(starter.contains("tone only"));
3725 }
3726
3727 #[test]
3728 fn talk_personas_parse_and_are_validated() {
3729 let dir = tempfile::tempdir().unwrap();
3730 let path = dir.path().join("magi.toml");
3731 std::fs::write(
3732 &path,
3733 "[[talk.personas]]\nid = \"rei\"\nname = \"Quiet\"\nprompt = \"Be brief.\"\n\n\
3734 [[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n",
3735 )
3736 .unwrap();
3737 let cfg = Config::load(&path).expect("loads");
3738 assert_eq!(cfg.talk.personas.len(), 2);
3739 let catalog = crate::persona::catalog(&cfg.talk.personas);
3740 let rei = catalog.iter().find(|p| p.id == "rei").unwrap();
3741 assert_eq!(
3742 (rei.name.as_str(), rei.prompt.as_str()),
3743 ("Quiet", "Be brief.")
3744 );
3745 assert_eq!(catalog.last().unwrap().id, "gendo");
3746
3747 for (body, needle) in [
3748 (
3749 "[[talk.personas]]\nid = \"\"\nname = \"n\"\nprompt = \"p\"\n",
3750 "empty `id`",
3751 ),
3752 (
3753 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \" \"\n",
3754 "empty `prompt`",
3755 ),
3756 (
3757 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n\
3758 [[talk.personas]]\nid = \"a\"\nname = \"m\"\nprompt = \"q\"\n",
3759 "more than once",
3760 ),
3761 (
3762 "[[talk.personas]]\nid = \"default\"\nname = \"n\"\nprompt = \"p\"\n",
3763 "cannot be redefined",
3764 ),
3765 ] {
3766 std::fs::write(&path, body).unwrap();
3767 let err = format!("{:#}", Config::load(&path).unwrap_err());
3768 assert!(err.contains(needle), "{needle}: {err}");
3769 }
3770 }
3771
3772 #[test]
3773 fn talk_operator_name_is_trimmed_and_validated() {
3774 let dir = tempfile::tempdir().unwrap();
3775 let path = dir.path().join("magi.toml");
3776 let load = |body: &str| {
3777 std::fs::write(&path, body).unwrap();
3778 Config::load(&path)
3779 };
3780 let ok = load("[talk]\noperator_name = \" Commander \"\n").expect("ok");
3781 assert_eq!(ok.talk.operator_name(), Some("Commander"));
3782 let blank = load("[talk]\noperator_name = \" \"\n").expect("blank");
3783 assert_eq!(blank.talk.operator_name(), None);
3784 assert!(load("[talk]\noperator_name = \"a\\nb\"\n").is_err());
3785 let long = "x".repeat(65);
3786 assert!(load(&format!("[talk]\noperator_name = \"{long}\"\n")).is_err());
3787 }
3788
3789 #[test]
3790 fn talk_persona_icon_parses_and_a_bad_shape_keeps_config_usable() {
3791 let dir = tempfile::tempdir().unwrap();
3792 let load = |body: &str| {
3793 let path = dir.path().join("c.toml");
3794 std::fs::write(&path, body).unwrap();
3795 Config::load(&path)
3796 };
3797 let ok = load(
3798 "[[talk.personas]]\nid = \"rei\"\nicon = \"~/rei.png\"\n\n\
3799 [[talk.personas]]\nid = \"default\"\nicon = \"data:image/png;base64,AAAA\"\n",
3800 )
3801 .unwrap();
3802 let c = crate::persona::catalog(&ok.talk.personas);
3803 assert_eq!(c[0].icon.as_deref(), Some("data:image/png;base64,AAAA"));
3804 assert_eq!(c[2].icon.as_deref(), Some("~/rei.png"));
3805 assert!(c[2].prompt.contains("Rei"), "built-in voice kept");
3806 let oversized = format!(
3807 "data:image/png;base64,{}",
3808 "A".repeat(crate::persona_icon::ICON_MAX_BYTES)
3809 );
3810 for bad in ["", "rei.png", "/a/b.svg", "/a/../b.png", &oversized] {
3811 for (id, fields) in [
3812 ("rei", ""),
3813 ("default", ""),
3814 ("custom", "name = \"Custom\"\nprompt = \"Keep calm\"\n"),
3815 ] {
3816 let body = format!("[[talk.personas]]\nid = \"{id}\"\nicon = \"{bad}\"\n{fields}");
3817 let cfg = load(&body).expect("bad icon must not invalidate config");
3818 let persona = crate::persona::find(&cfg.talk.personas, id).unwrap();
3819 assert_eq!(persona.id, id);
3820 assert!(crate::persona_icon::load(bad).is_err());
3821 }
3822 }
3823 let doc = Config::starter_toml();
3824 assert!(doc.contains("# icon = "));
3825 }
3826
3827 #[test]
3828 fn talk_personas_in_two_layers_are_refused() {
3829 let dir = tempfile::tempdir().unwrap();
3830 let machine = dir.path().join("machine.toml");
3831 let repo = dir.path().join("repo.toml");
3832 let one = "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n";
3833 std::fs::write(&machine, one).unwrap();
3834 std::fs::write(&repo, one.replace("\"a\"", "\"b\"")).unwrap();
3835 let err = format!("{:#}", Config::load_layers(&[machine, repo]).unwrap_err());
3836 assert!(err.contains("talk.personas"), "{err}");
3837 }
3838
3839 #[test]
3840 fn starter_toml_documents_role_lists_as_backup_order() {
3841 let starter = Config::starter_toml();
3842 assert!(starter.contains("also an ordered backup list"));
3843 assert!(starter.contains("codex then sonnet are spares"));
3844 }
3845
3846 #[test]
3850 fn a_repository_can_declare_a_linear_history_merge_style() {
3851 let dir = tempfile::tempdir().unwrap();
3852 let path = dir.path().join("magi.toml");
3853 std::fs::write(&path, "[merge]\nmode = \"none\"\nstyle = \"squash\"\n").unwrap();
3854 let parsed = Config::load(&path).expect("config must load");
3855 assert_eq!(parsed.merge.style, MergeStyle::Squash);
3856 }
3857
3858 #[test]
3859 fn later_layers_win_and_vars_render() {
3860 let dir = tempfile::tempdir().unwrap();
3861 let machine = dir.path().join("machine.toml");
3862 let project = dir.path().join("magi.toml");
3863 std::fs::write(
3865 &machine,
3866 "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
3867 [graph]\ncandidates = 3\nmax_parallel = 8\n",
3868 )
3869 .unwrap();
3870 std::fs::write(
3873 &project,
3874 "[vars]\ncache = \"/shared\"\n\n\
3875 [graph]\ncandidates = 2\n\n\
3876 [verify]\ngate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
3877 )
3878 .unwrap();
3879
3880 let cfg = Config::load_layers(&[machine, project]).expect("layered load");
3881 assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
3882 assert_eq!(cfg.graph.implementers, 2, "project layer wins");
3883 assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
3884 assert_eq!(
3885 cfg.verify.gate,
3886 ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
3887 );
3888 assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
3890 }
3891
3892 #[test]
3893 fn talk_defaults_to_an_hour_and_an_unwritten_config_still_gets_it() {
3894 let g = Graph::default();
3898 assert_eq!(g.timeout_talk, 3600);
3899
3900 let dir = tempfile::tempdir().unwrap();
3901 let path = dir.path().join("magi.toml");
3902 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
3903 let cfg = Config::load(&path).expect("must load without timeout_talk set");
3904 assert_eq!(cfg.graph.timeout_talk, 3600);
3905 }
3906
3907 #[test]
3908 fn an_overridden_talk_timeout_reaches_the_loaded_config() {
3909 let dir = tempfile::tempdir().unwrap();
3910 let path = dir.path().join("magi.toml");
3911 std::fs::write(&path, "[graph]\ntimeout_talk = 120\n").unwrap();
3912 let cfg = Config::load(&path).expect("must load");
3913 assert_eq!(cfg.graph.timeout_talk, 120);
3914 }
3915
3916 #[test]
3917 fn the_disk_defaults_are_the_measurements_made_up_front() {
3918 let cfg = Config::default();
3919 assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
3920 assert!(cfg.disk.auto_fold);
3921 assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
3922 assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
3923 }
3924
3925 #[test]
3926 fn an_unset_disk_section_is_the_safe_default() {
3927 let dir = tempfile::tempdir().unwrap();
3928 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
3929 let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
3930 assert_eq!(cfg.disk, Disk::default());
3931 }
3932
3933 #[test]
3934 fn env_is_available_to_templates_with_a_default() {
3935 let dir = tempfile::tempdir().unwrap();
3936 let path = dir.path().join("magi.toml");
3937 std::fs::write(
3945 &path,
3946 "[verify]\n\
3947 gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
3948 \"populated={{ env | length > 0 }}\"]\n",
3949 )
3950 .unwrap();
3951 let cfg = Config::load(&path).expect("env lookup must render");
3952 assert_eq!(cfg.verify.gate[0], "cache=fallback");
3953 assert_eq!(cfg.verify.gate[1], "populated=true");
3954 }
3955
3956 #[test]
3957 fn a_broken_template_names_the_file() {
3958 let dir = tempfile::tempdir().unwrap();
3959 let path = dir.path().join("magi.toml");
3960 std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
3961 let err = Config::load(&path).expect_err("must not silently ignore");
3962 assert!(err.to_string().contains("teravars"), "{err}");
3963 }
3964
3965 #[test]
3966 fn tera_syntax_in_comments_is_inert() {
3967 let dir = tempfile::tempdir().unwrap();
3971 let path = dir.path().join("magi.toml");
3972 std::fs::write(
3973 &path,
3974 "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
3975 [graph]\ncandidates = 2\n",
3976 )
3977 .unwrap();
3978 let cfg = Config::load(&path).expect("comments must be inert, not rendered");
3979 assert_eq!(cfg.graph.implementers, 2);
3980 }
3981
3982 #[test]
3983 fn agent_turn_cap_round_trips_and_never_extends_the_budget() {
3984 use std::time::Duration;
3985
3986 let mut s: AgentSpec =
3987 toml::from_str("id = 'slow'\nkind = 'command'\ncommand = ['true']\n").unwrap();
3988 let budget = Duration::from_millis(1500);
3989 assert_eq!(s.max_turn_secs, None);
3990 assert_eq!(s.turn_timeout(budget), budget);
3991 assert!(!toml::to_string(&s).unwrap().contains("max_turn_secs"));
3992 for (cap, expected) in [
3993 (1, Duration::from_secs(1)),
3994 (2, budget),
3995 (0, Duration::ZERO),
3996 ] {
3997 s.max_turn_secs = Some(cap);
3998 let saved = toml::to_string(&s).unwrap();
3999 let loaded: AgentSpec = toml::from_str(&saved).unwrap();
4000 assert_eq!(loaded.max_turn_secs, Some(cap));
4001 assert_eq!(loaded.turn_timeout(budget), expected);
4002 }
4003 }
4004
4005 #[test]
4006 fn opencode_defaults_to_file_delivery() {
4007 let mut s = spec("oc");
4008 s.kind = AgentKind::Opencode;
4009 assert_eq!(s.delivery(), Delivery::File);
4010 s.prompt_delivery = Some(Delivery::Argv);
4011 assert_eq!(s.delivery(), Delivery::Argv);
4012 }
4013 #[test]
4014 fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
4015 let g = Graph::default();
4020 assert!(
4021 g.land,
4022 "stopping at an open PR left the watching to a human"
4023 );
4024 assert!(
4025 g.land_approval,
4026 "on-by-default land is only defensible while this is also on"
4027 );
4028 assert!(g.land_rounds > 0, "a loop with no budget never terminates");
4029 assert!(
4030 g.hold_contested_merge,
4031 "a contested hand-off must still reach a human when approvals are off"
4032 );
4033 }
4034 #[test]
4035 fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
4036 let dir = tempfile::tempdir().unwrap();
4040 let machine = dir.path().join("machine.toml");
4041 let repo = dir.path().join("magi.toml");
4042 std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
4043 std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
4044
4045 let err = Config::load_layers(&[machine.clone(), repo.clone()])
4046 .expect_err("two layers naming one array must not merge silently");
4047 assert_eq!(
4048 err.downcast_ref::<ConfigFailure>().unwrap().stage,
4049 "config-merge"
4050 );
4051 let err = err.to_string();
4052 assert!(err.contains("roles.implementers"), "{err}");
4053 assert!(err.contains("machine.toml"), "{err}");
4056 assert!(err.contains("magi.toml"), "{err}");
4057 }
4058
4059 #[test]
4060 fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
4061 let dir = tempfile::tempdir().unwrap();
4064 let machine = dir.path().join("machine.toml");
4065 let repo = dir.path().join("magi.toml");
4066 std::fs::write(&machine, "[roles]\nchatter = \"opus\"\n").unwrap();
4067 std::fs::write(
4068 &repo,
4069 "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
4070 [roles]\nimplementers = [\"oc\"]\n",
4071 )
4072 .unwrap();
4073
4074 let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
4075 assert_eq!(primary(cfg.roles.chatter.as_ref()), Some("opus"));
4076 assert_eq!(cfg.roles.implementers, ["oc"]);
4077 assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
4078 }
4079
4080 #[test]
4081 fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
4082 let dir = tempfile::tempdir().unwrap();
4085 let machine = dir.path().join("machine.toml");
4086 let repo = dir.path().join("magi.toml");
4087 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
4088 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4089
4090 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4091 assert_eq!(
4092 cfg.verify.gate,
4093 [
4094 "editorconfig-checker".to_owned(),
4095 "cargo make check".to_owned()
4096 ],
4097 "low-priority (machine) command first, high-priority (repo) command after"
4098 );
4099 }
4100
4101 fn load_one(body: &str) -> Result<Config> {
4102 let dir = tempfile::tempdir().unwrap();
4103 let path = dir.path().join("magi.toml");
4104 std::fs::write(&path, body).unwrap();
4105 Config::load_layers(&[path])
4106 }
4107
4108 #[test]
4109 fn worktree_setup_defaults_to_empty_and_parses_steps() {
4110 assert!(Config::default().worktree.setup.is_empty());
4111 let cfg = load_one(
4112 "[worktree]\nsetup = [\n { copy = \".env.example -> .env\" },\n \
4113 { copy = \"x\", optional = true },\n { run = \"true\", timeout_secs = 5 },\n]\n",
4114 )
4115 .unwrap();
4116 assert_eq!(cfg.worktree.setup.len(), 3);
4117 assert!(cfg.worktree.setup[1].optional);
4118 assert_eq!(cfg.worktree.setup[2].timeout_secs, Some(5));
4119 }
4120
4121 #[test]
4122 fn worktree_setup_rejects_malformed_steps() {
4123 for bad in [
4124 "{ copy = \"a\", run = \"b\" }",
4125 "{ optional = true }",
4126 "{ copy = \"a -> ../b\" }",
4127 "{ copy = \"a -> /abs\" }",
4128 "{ copy = \"a -> .git/config\" }",
4129 "{ run = \"b\", optional = true }",
4130 "{ copy = \"a\", timeout_secs = 3 }",
4131 "{ run = \"b\", bogus = 1 }",
4132 ] {
4133 let body = format!("[worktree]\nsetup = [{bad}]\n");
4134 assert!(load_one(&body).is_err(), "{bad}");
4135 }
4136 }
4137
4138 #[test]
4139 fn worktree_setup_in_two_layers_is_refused() {
4140 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, "[worktree]\nsetup = [{ run = \"a\" }]\n").unwrap();
4144 std::fs::write(&repo, "[worktree]\nsetup = [{ run = \"b\" }]\n").unwrap();
4145 assert!(Config::load_layers(&[machine, repo]).is_err());
4146 }
4147
4148 #[test]
4149 fn starter_toml_documents_worktree_setup() {
4150 let starter = Config::starter_toml();
4151 assert!(starter.contains("# [worktree]") && starter.contains("setup = ["));
4152 let body = starter.replace("# [worktree]", "[worktree]");
4154 let mut out = String::new();
4155 let mut live = false;
4156 for line in body.lines() {
4157 if line == "[worktree]" {
4158 live = true;
4159 } else if live && !line.starts_with("# ") {
4160 live = false;
4161 }
4162 out.push_str(&if live {
4163 line.replacen("# ", "", 1)
4164 } else {
4165 line.to_owned()
4166 });
4167 out.push('\n');
4168 }
4169 let cfg = load_one(&out).expect("uncommented example loads");
4170 assert_eq!(cfg.worktree.setup.len(), 3);
4171 }
4172
4173 #[test]
4174 fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
4175 let dir = tempfile::tempdir().unwrap();
4176 let machine = dir.path().join("machine.toml");
4177 let repo = dir.path().join("magi.toml");
4178 std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
4179 std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
4180
4181 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4182 assert_eq!(
4183 cfg.verify.e2e,
4184 ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
4185 );
4186 }
4187
4188 #[test]
4189 fn two_layers_declaring_repos_roots_are_both_scanned() {
4190 let dir = tempfile::tempdir().unwrap();
4191 let machine = dir.path().join("machine.toml");
4192 let repo = dir.path().join("magi.toml");
4193 std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
4194 std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
4195
4196 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4197 assert_eq!(
4198 cfg.repos.roots,
4199 [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
4200 );
4201 }
4202
4203 #[test]
4204 fn duplicate_gate_commands_across_layers_both_run() {
4205 let dir = tempfile::tempdir().unwrap();
4208 let machine = dir.path().join("machine.toml");
4209 let repo = dir.path().join("magi.toml");
4210 std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
4211 std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
4212
4213 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4214 assert_eq!(
4215 cfg.verify.gate,
4216 ["same-command".to_owned(), "same-command".to_owned()]
4217 );
4218 }
4219
4220 #[test]
4221 fn notify_command_is_still_refused_across_two_layers() {
4222 let dir = tempfile::tempdir().unwrap();
4224 let machine = dir.path().join("machine.toml");
4225 let repo = dir.path().join("magi.toml");
4226 std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
4227 std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
4228
4229 let err = Config::load_layers(&[machine.clone(), repo.clone()])
4230 .expect_err("an argv split across layers must not concatenate");
4231 assert_eq!(
4232 err.downcast_ref::<ConfigFailure>().unwrap().stage,
4233 "config-merge"
4234 );
4235 let err = err.to_string();
4236 assert!(err.contains("notify.command"), "{err}");
4237 assert!(err.contains("machine.toml"), "{err}");
4238 assert!(err.contains("magi.toml"), "{err}");
4239 }
4240
4241 #[test]
4242 fn one_layer_declaring_verify_gate_runs_unchanged() {
4243 let dir = tempfile::tempdir().unwrap();
4246 let path = dir.path().join("magi.toml");
4247 std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4248
4249 let cfg = Config::load(&path).expect("single layer must still load");
4250 assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
4251 }
4252
4253 #[test]
4254 fn layered_parse_failures_name_the_failing_input() {
4255 let dir = tempfile::tempdir().unwrap();
4256 let a = dir.path().join("a.toml");
4257 let b = dir.path().join("b.toml");
4258 std::fs::write(&a, "[graph").unwrap();
4259 std::fs::write(&b, "[verify").unwrap();
4260 let paths = [a.clone(), b.clone()];
4261 let first = Config::load_layers(&paths).unwrap_err();
4262 let first_cause = first.downcast_ref::<ConfigFailure>().unwrap();
4263 assert_eq!(first_cause.stage, "config-parse");
4264 assert_eq!(first_cause.target, serde_json::to_string(&[&a]).unwrap());
4265 std::fs::write(&a, "").unwrap();
4266 let second = Config::load_layers(&paths).unwrap_err();
4267 let second_cause = second.downcast_ref::<ConfigFailure>().unwrap();
4268 assert_eq!(second_cause.stage, "config-parse");
4269 assert_eq!(second_cause.target, serde_json::to_string(&[&b]).unwrap());
4270 assert_ne!(first_cause.target, second_cause.target);
4271 }
4272
4273 #[test]
4274 fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
4275 let dir = tempfile::tempdir().unwrap();
4276 let machine = dir.path().join("machine.toml");
4277 let repo = dir.path().join("magi.toml");
4278 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
4279 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4280 let paths = vec![machine.clone(), repo.clone()];
4281
4282 let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
4283 let described =
4284 Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
4285 assert!(described.contains("editorconfig-checker && cargo make check"));
4286 assert!(
4287 described.contains(&machine.display().to_string()),
4288 "{described}"
4289 );
4290 assert!(
4291 described.contains(&repo.display().to_string()),
4292 "{described}"
4293 );
4294
4295 let single = vec![repo.clone()];
4297 let solo_cfg = Config::load_layers(&single).expect("single layer loads");
4298 let solo_described =
4299 Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
4300 assert_eq!(solo_described, "cargo make check");
4301 }
4302
4303 mod remote_layers {
4304 use super::*;
4305
4306 fn git(dir: &Path, args: &[&str]) {
4307 use crate::proc::Quiet as _;
4308 let out = std::process::Command::new("git")
4309 .args(args)
4310 .quiet()
4311 .current_dir(dir)
4312 .output()
4313 .unwrap();
4314 assert!(out.status.success(), "git {args:?}: {out:?}");
4315 }
4316
4317 fn fixture(remote: &str, disk: &str) -> (tempfile::TempDir, PathBuf) {
4320 let tmp = tempfile::tempdir().unwrap();
4321 let bare = tmp.path().join("o.git");
4322 git(tmp.path(), &["init", "--bare", "-b", "trunk", "o.git"]);
4323 let repo = tmp.path().join("repo");
4324 std::fs::create_dir_all(&repo).unwrap();
4325 git(&repo, &["init", "-b", "trunk"]);
4326 git(&repo, &["config", "user.name", "t"]);
4327 git(&repo, &["config", "user.email", "t@example.com"]);
4328 std::fs::write(repo.join("magi.toml"), remote).unwrap();
4329 git(&repo, &["add", "-A"]);
4330 git(&repo, &["commit", "-m", "x"]);
4331 git(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
4332 git(&repo, &["push", "origin", "trunk"]);
4333 git(&repo, &["fetch", "origin"]);
4334 git(&repo, &["remote", "set-head", "origin", "trunk"]);
4335 std::fs::write(repo.join("magi.toml"), disk).unwrap();
4336 (tmp, repo)
4337 }
4338
4339 #[tokio::test]
4340 async fn branch_owner_holds_only_add_literal_true_values() {
4341 for (text, expected) in [
4342 ("[graph]\nland_approval = true\n", true),
4343 ("[graph]\nland_approval = false\n", false),
4344 ("[graph]\nland = true\n", false),
4345 ("[graph\n", false),
4346 ("[graph]\nland_approval = \"yes\"\n", false),
4347 ("[graph]\nland_approval = 1\n", false),
4348 ] {
4349 let (_tmp, repo) = fixture(text, "[graph]\nland_approval = false\n");
4350 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
4351 let (holds, _) = branch_owner_holds(&repo, &head).await;
4352 assert_eq!(
4353 holds.contains(&(OwnerHold::LandApproval, "magi.toml".into())),
4354 expected
4355 );
4356 assert!(
4357 !holds
4358 .iter()
4359 .any(|(h, _)| *h == OwnerHold::HoldContestedMerge)
4360 );
4361 for base in [false, true] {
4362 let mut cfg = Config::default();
4363 cfg.graph.land_approval = base;
4364 let mut state = crate::run::RunState::new(
4365 repo.clone(),
4366 "trunk".into(),
4367 head.clone(),
4368 "review".into(),
4369 cfg,
4370 );
4371 state.observe_branch_owner_holds(&head).await;
4372 assert!(
4373 state.branch_owner_holds.is_empty(),
4374 "competition candidates are excluded"
4375 );
4376 state.reviewed_commits = Some(Vec::new());
4377 state.observe_branch_owner_holds(&head).await;
4378 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base || expected);
4379 }
4380 }
4381 }
4382
4383 #[tokio::test]
4384 async fn branch_owner_holds_missing_and_unreadable_preserve_base() {
4385 let (_tmp, repo) = fixture(
4386 "[graph]\nland_approval = true\n",
4387 "[graph]\nland_approval = true\n",
4388 );
4389 git(&repo, &["rm", "magi.toml"]);
4390 std::fs::create_dir(repo.join(".magi")).unwrap();
4391 std::fs::write(
4392 repo.join(".magi/config.toml"),
4393 "[graph]\nhold_contested_merge = true\n",
4394 )
4395 .unwrap();
4396 git(&repo, &["add", "."]);
4397 git(&repo, &["commit", "-m", "nested hold"]);
4398 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
4399 let (holds, _) = branch_owner_holds(&repo, &head).await;
4400 assert_eq!(
4401 holds,
4402 [(OwnerHold::HoldContestedMerge, ".magi/config.toml".into())]
4403 );
4404 let (holds, diagnostics) =
4405 branch_owner_holds(&repo, "0000000000000000000000000000000000000000").await;
4406 assert!(holds.is_empty());
4407 assert!(!diagnostics.is_empty());
4408 let (holds, diagnostics) = branch_owner_holds(&repo, "").await;
4409 assert!(holds.is_empty());
4410 assert!(!diagnostics.is_empty());
4411 for base in [false, true] {
4412 let mut cfg = Config::default();
4413 cfg.graph.land_approval = base;
4414 let mut state = crate::run::RunState::new(
4415 repo.clone(),
4416 "trunk".into(),
4417 head.clone(),
4418 "review".into(),
4419 cfg,
4420 );
4421 state.reviewed_commits = Some(Vec::new());
4422 state.observe_branch_owner_holds(&head).await;
4423 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
4424 state
4425 .observe_branch_owner_holds("0000000000000000000000000000000000000000")
4426 .await;
4427 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
4428 }
4429 }
4430
4431 #[test]
4432 fn reads_the_remote_blob_not_the_working_tree() {
4433 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4434 let (cfg, _) = Config::discover(&repo, None).unwrap();
4435 assert_eq!(cfg.graph.implementers, 2);
4436 }
4437
4438 #[test]
4439 fn detached_head_still_reads_the_remote() {
4440 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4441 git(&repo, &["checkout", "--detach"]);
4442 let (cfg, _) = Config::discover(&repo, None).unwrap();
4443 assert_eq!(cfg.graph.implementers, 2);
4444 }
4445
4446 #[test]
4447 fn a_missing_ref_is_an_error_not_a_fallback() {
4448 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4449 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
4450 let err = format!("{:#}", Config::discover(&repo, None).unwrap_err());
4451 assert!(err.contains("origin"), "{err}");
4452 }
4453
4454 #[test]
4455 fn merge_base_in_the_checkout_locates_the_ref() {
4456 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
4457 assert!(Config::discover(&repo, None).is_err());
4458 }
4459
4460 #[test]
4461 fn the_magi_dir_layer_is_read_too() {
4462 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4463 std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
4464 std::fs::create_dir_all(repo.join(".magi")).unwrap();
4465 std::fs::write(repo.join(".magi/config.toml"), "[graph]\njudges = 3\n").unwrap();
4466 git(&repo, &["add", "-A"]);
4467 git(&repo, &["commit", "-m", "y"]);
4468 git(&repo, &["push", "origin", "trunk"]);
4469 git(&repo, &["fetch", "origin"]);
4470 let (cfg, layers) = Config::discover(&repo, None).unwrap();
4471 assert_eq!((cfg.graph.implementers, cfg.graph.judges), (2, 3));
4472 assert_eq!(layers.len(), 2);
4473 }
4474
4475 #[test]
4476 fn an_include_in_a_repository_layer_resolves_against_the_same_commit() {
4477 let (_t, repo) = fixture("include = [\"gate.toml\"]\n", "");
4478 std::fs::write(repo.join("magi.toml"), "include = [\"gate.toml\"]\n").unwrap();
4479 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 2\n").unwrap();
4480 git(&repo, &["add", "-A"]);
4481 git(&repo, &["commit", "-m", "inc"]);
4482 git(&repo, &["push", "origin", "trunk"]);
4483 git(&repo, &["fetch", "origin"]);
4484 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 9\n").unwrap();
4486 let (cfg, _) = Config::discover(&repo, None).unwrap();
4487 assert_eq!(cfg.graph.implementers, 2);
4488 }
4489
4490 #[test]
4491 fn a_machine_layer_base_is_rendered_before_locating_the_ref() {
4492 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
4493 let m = t.path().join("machine.toml");
4494 std::fs::write(
4495 &m,
4496 "[merge]\nbase = \"{{ env.MAGI_TEST_NO_SUCH | default(value='trunk') }}\"\n",
4497 )
4498 .unwrap();
4499 let (remote, base) = {
4500 let probe = probe_merge(&m, &repo).unwrap();
4501 (probe.remote, probe.base)
4502 };
4503 assert_eq!((remote, base), (None, Some("trunk".to_owned())));
4504 }
4505
4506 #[test]
4507 fn a_machine_layer_base_sees_the_checkouts_repo_name() {
4508 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4509 let m = t.path().join("machine.toml");
4510 std::fs::write(&m, "[merge]\nbase = \"{{ repo_name }}\"\n").unwrap();
4511 let probe = probe_merge(&m, &repo).unwrap();
4512 assert_eq!(probe.base.as_deref(), Some("repo"));
4513 }
4514
4515 #[test]
4516 fn every_include_form_is_recognised() {
4517 assert!(declares_include("include = [\"a.toml\"]\n"));
4518 assert!(declares_include("\"include\" = [\"a.toml\"]\n"));
4519 assert!(declares_include("teravars = { include = [\"a.toml\"] }\n"));
4520 assert!(declares_include("[teravars]\ninclude = [\"a.toml\"]\n"));
4521 assert!(!declares_include("[graph]\ncandidates = 2\n"));
4522 }
4523
4524 #[test]
4525 fn an_explicit_config_is_read_as_named() {
4526 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4527 let own = t.path().join("own.toml");
4528 std::fs::write(&own, "[graph]\ncandidates = 4\n").unwrap();
4529 let (cfg, _) = Config::discover(&repo, Some(&own)).unwrap();
4530 assert_eq!(cfg.graph.implementers, 4);
4531 }
4532
4533 #[test]
4534 fn discover_fetched_fails_when_the_fetch_does() {
4535 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4536 std::fs::remove_dir_all(t.path().join("o.git")).unwrap();
4537 let rt = tokio::runtime::Builder::new_current_thread()
4538 .enable_all()
4539 .build()
4540 .unwrap();
4541 let err = rt
4542 .block_on(Config::discover_fetched(&repo, None))
4543 .unwrap_err();
4544 assert!(format!("{err:#}").contains("fetch"), "{err:#}");
4545 }
4546
4547 #[test]
4548 fn fetch_and_remote_parse_failures_have_distinct_verified_causes() {
4549 let (tmp, repo) = fixture("[graph\ncandidates = 2\n", "");
4550 let remote = tmp.path().join("o.git");
4551 let offline = tmp.path().join("offline.git");
4552 std::fs::rename(&remote, &offline).unwrap();
4553 let rt = tokio::runtime::Builder::new_current_thread()
4554 .enable_all()
4555 .build()
4556 .unwrap();
4557 let fetch = rt
4558 .block_on(Config::discover_fetched(&repo, None))
4559 .unwrap_err();
4560 let fetch_cause = fetch.downcast_ref::<ConfigFailure>().unwrap();
4561 assert_eq!(fetch_cause.stage, "config-fetch");
4562 assert_eq!(fetch_cause.target, "origin/trunk");
4563
4564 std::fs::rename(&offline, &remote).unwrap();
4565 let parse = rt
4566 .block_on(Config::discover_fetched(&repo, None))
4567 .unwrap_err();
4568 let parse_cause = parse.downcast_ref::<ConfigFailure>().unwrap();
4569 assert_eq!(parse_cause.stage, "config-parse");
4570 assert!(parse_cause.target.contains("magi.toml"));
4571 assert!(
4572 !parse_cause.target.contains("/magi/config/"),
4573 "cache commit paths are incidental"
4574 );
4575 assert_ne!(fetch_cause.stage, parse_cause.stage);
4576 }
4577
4578 #[test]
4579 fn discover_fetched_survives_a_fetch_that_leaves_no_origin_head() {
4580 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4583 git(&repo, &["remote", "set-head", "origin", "-d"]);
4584 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
4585 git(
4586 &repo,
4587 &["config", "remote.origin.followRemoteHEAD", "never"],
4588 );
4589 let rt = tokio::runtime::Builder::new_current_thread()
4590 .enable_all()
4591 .build()
4592 .unwrap();
4593 let (cfg, _) = rt.block_on(Config::discover_fetched(&repo, None)).unwrap();
4594 assert_eq!(cfg.graph.implementers, 2);
4595 }
4596
4597 #[test]
4598 fn a_non_git_directory_reads_its_files() {
4599 let dir = tempfile::tempdir().unwrap();
4600 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 4\n").unwrap();
4601 let (cfg, _) = Config::discover(dir.path(), None).unwrap();
4602 assert_eq!(cfg.graph.implementers, 4);
4603 }
4604 }
4605
4606 #[test]
4607 fn github_language_defaults_to_english_and_accepts_japanese() {
4608 let default: Graph = toml::from_str("").unwrap();
4609 assert_eq!(default.github_language, "en");
4610 assert!(default.github_english() && default.language_gate());
4611 let ja: Graph = toml::from_str("github_language = \"ja\"").unwrap();
4612 assert!(!ja.github_english() && !ja.language_gate());
4613 let only_ops: Graph = toml::from_str("language = \"ja\"").unwrap();
4615 assert!(only_ops.language_gate());
4616 let off: Graph = toml::from_str("github_text_guard = false").unwrap();
4617 assert!(!off.language_gate() && off.github_english());
4618 assert!(Config::starter_toml().contains("github_language = \"en\""));
4619 }
4620}