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}
198
199impl AgentSpec {
200 pub fn delivery(&self) -> Delivery {
206 self.prompt_delivery.unwrap_or(match self.kind {
207 AgentKind::Claude | AgentKind::Command => Delivery::Stdin,
208 AgentKind::Codex => Delivery::Stdin,
212 AgentKind::Omp => Delivery::Stdin,
216 AgentKind::Opencode | AgentKind::Antigravity => Delivery::File,
217 })
218 }
219
220 pub fn display(&self) -> String {
222 match &self.model {
223 Some(m) => format!("{} ({}:{m})", self.id, self.kind.as_str()),
224 None => format!("{} ({})", self.id, self.kind.as_str()),
225 }
226 }
227}
228
229#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
236#[serde(untagged)]
237pub enum AgentChoice {
238 One(String),
240 Chain(Vec<String>),
242}
243
244impl AgentChoice {
245 pub fn ids(&self) -> Vec<&str> {
247 let all: Vec<&str> = match self {
248 Self::One(id) => vec![id.as_str()],
249 Self::Chain(ids) => ids.iter().map(String::as_str).collect(),
250 };
251 all.into_iter()
252 .map(str::trim)
253 .filter(|id| !id.is_empty())
254 .collect()
255 }
256
257 pub fn primary(&self) -> Option<&str> {
259 self.ids().into_iter().next()
260 }
261}
262
263impl From<&str> for AgentChoice {
264 fn from(id: &str) -> Self {
265 Self::One(id.to_owned())
266 }
267}
268
269pub fn primary(choice: Option<&AgentChoice>) -> Option<&str> {
271 choice.and_then(AgentChoice::primary)
272}
273
274#[derive(Debug, Clone, Default, Deserialize, Serialize)]
277#[serde(deny_unknown_fields, default)]
278pub struct Roles {
279 pub implementers: Vec<String>,
281 pub judges: Vec<String>,
283 pub reviewers: Vec<String>,
285 pub fixer: Option<AgentChoice>,
294 pub chatter: Option<AgentChoice>,
308 pub dupes_judge: Option<AgentChoice>,
312 pub conductor: Option<AgentChoice>,
325 pub advisors: Vec<String>,
336 pub synthesizer: Option<AgentChoice>,
349 pub language_judge: Option<AgentChoice>,
358}
359
360#[derive(Debug, Clone, Deserialize, Serialize)]
362#[serde(deny_unknown_fields, default)]
363pub struct Graph {
364 pub github_text_guard: bool,
366 pub github_language: String,
372 #[serde(alias = "candidates")]
404 pub implementers: usize,
405 #[serde(default)]
407 pub selected_implementer: Option<String>,
408 pub judges: usize,
410 pub deliberate_rounds: usize,
412 pub reviewers: usize,
420 pub review_rounds: usize,
422 pub gate_fix_rounds: usize,
428 pub max_parallel: usize,
430 pub language: String,
432 pub sessions: bool,
440 pub timeout_implement: u64,
442 pub timeout_judge: u64,
444 pub timeout_review: u64,
446 pub timeout_verify: Option<u64>,
455 pub timeout_fix: u64,
457 pub timeout_talk: u64,
465 pub timeout_resource_wait: u64,
474 pub retries: usize,
476 pub worktree_root: Option<PathBuf>,
478 pub land: bool,
491 pub land_rounds: usize,
493 pub rerun_flaky_checks: bool,
501 pub land_approval: bool,
512 pub hold_contested_merge: bool,
523 pub file_followups: bool,
530 pub release_deputy_followups: bool,
538 pub answer_timeout: u64,
542 pub incomplete_review: IncompleteReviewPolicy,
545 pub e2e_every_round: bool,
563 pub advise: bool,
577 pub advisors: usize,
582 pub graft_runner_up: bool,
591}
592
593impl Default for Graph {
594 fn default() -> Self {
595 Self {
596 github_text_guard: true,
597 github_language: "en".into(),
598 implementers: 1,
599 selected_implementer: None,
600 judges: 3,
601 deliberate_rounds: 1,
602 reviewers: 3,
603 review_rounds: 6,
604 gate_fix_rounds: 1,
605 max_parallel: 4,
606 language: "en".to_owned(),
607 sessions: true,
608 timeout_implement: 3600,
609 timeout_judge: 1200,
610 timeout_review: 1200,
611 timeout_verify: None,
612 timeout_fix: 1800,
613 timeout_talk: 3600,
614 timeout_resource_wait: 1800,
615 retries: 1,
616 worktree_root: None,
617 land: true,
618 land_rounds: 4,
619 rerun_flaky_checks: true,
620 land_approval: true,
621 hold_contested_merge: true,
622 file_followups: true,
623 release_deputy_followups: true,
624 answer_timeout: 86_400,
625 incomplete_review: IncompleteReviewPolicy::Block,
626 e2e_every_round: false,
627 advise: true,
628 advisors: 3,
629 graft_runner_up: true,
630 }
631 }
632}
633
634impl Graph {
635 pub fn verify_timeout(&self) -> u64 {
639 self.timeout_verify.unwrap_or(self.timeout_review)
640 }
641
642 pub fn language_gate(&self) -> bool {
645 self.github_text_guard && self.github_english()
646 }
647
648 pub fn github_english(&self) -> bool {
650 crate::lang::is_english(&self.github_language)
651 }
652}
653
654#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
661#[serde(rename_all = "lowercase")]
662pub enum IncompleteReviewPolicy {
663 Block,
667 Warn,
672}
673
674#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
676#[serde(rename_all = "lowercase")]
677pub enum LeakPolicy {
678 Warn,
680 Redact,
682 Fail,
684}
685
686#[derive(Debug, Clone, Deserialize, Serialize)]
693#[serde(deny_unknown_fields, default)]
694pub struct Blind {
695 pub commit_msg_hook: bool,
698 pub strip_lines: Vec<String>,
702 pub vendor_tokens: Vec<String>,
704 pub on_leak: LeakPolicy,
706 pub seed: Option<u64>,
709}
710
711impl Default for Blind {
712 fn default() -> Self {
713 Self {
714 commit_msg_hook: true,
715 strip_lines: [
716 "Co-Authored-By:",
717 "Signed-off-by:",
718 "Assisted-by:",
719 "Generated-by:",
720 "Generated with",
721 "\u{1f916}",
722 ]
723 .iter()
724 .map(|s| (*s).to_owned())
725 .collect(),
726 vendor_tokens: [
727 "claude",
728 "anthropic",
729 "codex",
730 "openai",
731 "chatgpt",
732 "gemini",
733 "grok",
734 "xai",
735 "copilot",
736 "opencode",
737 "qoder",
738 "cursor",
739 "\u{1f916}",
740 ]
741 .iter()
742 .map(|s| (*s).to_owned())
743 .collect(),
744 on_leak: LeakPolicy::Warn,
745 seed: None,
746 }
747 }
748}
749
750#[derive(Debug, Clone, Default, Deserialize, Serialize)]
752#[serde(deny_unknown_fields, default)]
753pub struct Verify {
754 pub e2e: Vec<String>,
757 pub gate: Vec<String>,
759 #[serde(default)]
768 pub pre_gate: Vec<String>,
769 pub shell: Option<Vec<String>>,
772}
773
774impl Verify {
775 pub fn cache_dir(&self) -> Option<PathBuf> {
781 self.e2e
782 .iter()
783 .chain(self.gate.iter())
784 .find_map(|cmd| crate::disk::extract_cargo_target_dir(cmd))
785 }
786
787 pub fn cargo_manifests(&self) -> Vec<PathBuf> {
790 let all: Vec<String> = self.e2e.iter().chain(self.gate.iter()).cloned().collect();
791 crate::cache::extract_manifest_paths(&all)
792 }
793}
794
795#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
797#[serde(deny_unknown_fields, default)]
798pub struct Worktree {
799 pub setup: Vec<SetupStep>,
802}
803
804#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
806#[serde(deny_unknown_fields, default)]
807pub struct SetupStep {
808 pub copy: Option<String>,
811 pub optional: bool,
813 pub run: Option<String>,
815 pub timeout_secs: Option<u64>,
818}
819
820impl Worktree {
821 pub fn validate(&self) -> Result<()> {
823 for (i, step) in self.setup.iter().enumerate() {
824 let n = i + 1;
825 match (&step.copy, &step.run) {
826 (Some(c), None) => {
827 if step.timeout_secs.is_some() {
828 bail!("[worktree] setup step {n}: `timeout_secs` applies to `run` only");
829 }
830 crate::worktree_setup::validate_copy(c)
831 .with_context(|| format!("[worktree] setup step {n}"))?;
832 }
833 (None, Some(r)) => {
834 if r.trim().is_empty() {
835 bail!("[worktree] setup step {n}: `run` is empty");
836 }
837 if step.optional {
838 bail!("[worktree] setup step {n}: `optional` applies to `copy` only");
839 }
840 }
841 _ => bail!("[worktree] setup step {n} must set exactly one of `copy` and `run`"),
842 }
843 }
844 Ok(())
845 }
846}
847
848#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
858#[serde(deny_unknown_fields, default)]
859pub struct Disk {
860 pub min_free_bytes: u64,
869 pub auto_fold: bool,
875 pub fold_grace_secs: u64,
883 pub cache_limit_bytes: u64,
895 pub worktree_limit_bytes: u64,
897 pub worktree_reclaim_bytes: u64,
899 pub retained_attempt_limit: usize,
903}
904
905impl Default for Disk {
906 fn default() -> Self {
907 Self {
908 min_free_bytes: 8 * 1024 * 1024 * 1024,
909 auto_fold: true,
910 fold_grace_secs: 6 * 60 * 60,
911 cache_limit_bytes: 10 * 1024 * 1024 * 1024,
912 worktree_limit_bytes: 10 * 1024 * 1024 * 1024,
913 worktree_reclaim_bytes: 16 * 1024 * 1024 * 1024,
914 retained_attempt_limit: 8,
915 }
916 }
917}
918
919#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
921#[serde(rename_all = "lowercase")]
922pub enum MergeMode {
923 None,
926 Local,
929 Pr,
933}
934
935#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
949#[serde(rename_all = "lowercase")]
950pub enum MergeStyle {
951 #[default]
956 Merge,
957 Squash,
963 Rebase,
969}
970
971#[derive(Debug, Clone, Deserialize, Serialize)]
973#[serde(deny_unknown_fields, default)]
974pub struct Merge {
975 pub mode: MergeMode,
978 pub base: Option<String>,
980 pub style: MergeStyle,
983 pub remote: String,
985 pub release_bump: bool,
998}
999
1000impl Default for Merge {
1001 fn default() -> Self {
1002 Self {
1003 mode: MergeMode::None,
1004 base: None,
1005 style: MergeStyle::default(),
1006 remote: "origin".to_owned(),
1007 release_bump: true,
1008 }
1009 }
1010}
1011
1012#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1014#[serde(rename_all = "lowercase")]
1015pub enum UpdateMode {
1016 Off,
1018 Notify,
1021 Install,
1023}
1024
1025#[derive(Debug, Clone, Deserialize, Serialize)]
1027#[serde(deny_unknown_fields, default)]
1028pub struct Update {
1029 pub mode: UpdateMode,
1031 pub interval: Option<String>,
1033}
1034
1035impl Default for Update {
1036 fn default() -> Self {
1037 Self {
1038 mode: UpdateMode::Notify,
1039 interval: None,
1040 }
1041 }
1042}
1043
1044#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1046#[serde(rename_all = "lowercase")]
1047pub enum ReleaseMode {
1048 #[default]
1051 Actions,
1052 Local,
1056}
1057
1058#[derive(Debug, Clone, Deserialize, Serialize)]
1060#[serde(deny_unknown_fields, default)]
1061pub struct Release {
1062 pub mode: ReleaseMode,
1065 pub commands: Vec<String>,
1072 pub timeout_minutes: u64,
1074}
1075
1076impl Default for Release {
1077 fn default() -> Self {
1078 Self {
1079 mode: ReleaseMode::Actions,
1080 commands: Vec::new(),
1081 timeout_minutes: 30,
1082 }
1083 }
1084}
1085
1086impl Release {
1087 pub fn is_local(&self) -> bool {
1089 self.mode == ReleaseMode::Local
1090 }
1091}
1092
1093#[derive(Debug, Clone, Deserialize, Serialize)]
1095#[serde(try_from = "CoordinationFields")]
1096pub struct Coordination {
1097 pub contract_file: String,
1099 pub contract_token: String,
1101 pub lock_file: String,
1103}
1104
1105#[derive(Deserialize, Default)]
1106#[serde(deny_unknown_fields, default)]
1107struct CoordinationFields {
1108 contract_file: String,
1109 contract_token: String,
1110 lock_file: String,
1111}
1112
1113impl TryFrom<CoordinationFields> for Coordination {
1114 type Error = anyhow::Error;
1115
1116 fn try_from(fields: CoordinationFields) -> Result<Self> {
1117 for (key, name) in [
1118 ("coordination.contract_file", &fields.contract_file),
1119 ("coordination.lock_file", &fields.lock_file),
1120 ] {
1121 if name.trim().is_empty()
1122 || name != name.trim()
1123 || name == "."
1124 || name.contains("..")
1125 || name.contains(['/', '\\', ':', '\0'])
1126 {
1127 bail!(
1128 "{key} must be a plain file name inside the Git common directory (no separators or '..')"
1129 );
1130 }
1131 }
1132 let token = &fields.contract_token;
1133 if token.is_empty() || token.trim() != token || token.chars().any(char::is_control) {
1134 bail!(
1135 "coordination.contract_token must be a nonempty single-line token without surrounding whitespace"
1136 );
1137 }
1138 Ok(Self {
1139 contract_file: fields.contract_file,
1140 contract_token: fields.contract_token,
1141 lock_file: fields.lock_file,
1142 })
1143 }
1144}
1145
1146#[cfg(test)]
1147pub(crate) fn test_coordination() -> Option<Coordination> {
1148 Some(Coordination {
1149 contract_file: "updater.contract".into(),
1150 contract_token: "test-protocol-v1".into(),
1151 lock_file: "updater.lock".into(),
1152 })
1153}
1154
1155#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1157#[serde(deny_unknown_fields, default)]
1158pub struct Config {
1159 pub coordination: Option<Coordination>,
1161 pub agents: Vec<AgentSpec>,
1163 pub roles: Roles,
1165 pub graph: Graph,
1167 pub blind: Blind,
1169 pub verify: Verify,
1171 pub worktree: Worktree,
1173 pub disk: Disk,
1175 pub merge: Merge,
1177 pub update: Update,
1179 pub prompts: Prompts,
1181 pub notify: Notify,
1183 pub repos: Repos,
1186 pub talk: Talk,
1188 pub daemon: Daemon,
1190 pub release: Release,
1192 pub context_windows: BTreeMap<String, u64>,
1195}
1196
1197const BUILTIN_CONTEXT_WINDOWS: &[(&str, u64)] = &[
1207 ("claude-opus-4", 200_000),
1208 ("claude-sonnet-4", 200_000),
1209 ("claude-haiku-4", 200_000),
1210 ("claude-3", 200_000),
1211 ("opus", 200_000),
1212 ("sonnet", 200_000),
1213 ("haiku", 200_000),
1214 ("gpt-5", 400_000),
1215 ("gpt-4.1", 1_000_000),
1216 ("gpt-4o", 128_000),
1217 ("o3", 200_000),
1218 ("o4-mini", 200_000),
1219 ("gemini-2.5", 1_000_000),
1220 ("deepseek", 128_000),
1221];
1222
1223impl Config {
1224 pub fn context_window(&self, model: &str) -> Option<u64> {
1229 fn lookup<'a>(model: &str, entries: impl Iterator<Item = (&'a str, u64)>) -> Option<u64> {
1230 let mut best: Option<(usize, u64)> = None;
1231 for (key, window) in entries {
1232 if key == model {
1233 return Some(window);
1234 }
1235 if model.starts_with(key) && best.is_none_or(|(len, _)| key.len() > len) {
1236 best = Some((key.len(), window));
1237 }
1238 }
1239 best.map(|(_, w)| w)
1240 }
1241 lookup(
1242 model,
1243 self.context_windows.iter().map(|(k, w)| (k.as_str(), *w)),
1244 )
1245 .or_else(|| lookup(model, BUILTIN_CONTEXT_WINDOWS.iter().copied()))
1246 }
1247}
1248
1249#[derive(Debug, Clone, Deserialize, Serialize)]
1259#[serde(deny_unknown_fields, default)]
1260pub struct Daemon {
1261 pub max_concurrent_runs: usize,
1282 pub pause_for_interrupts: bool,
1298 pub max_deputies: usize,
1305 pub release_stall_minutes: u64,
1312}
1313
1314impl Default for Daemon {
1315 fn default() -> Self {
1316 Self {
1317 max_concurrent_runs: 1,
1318 pause_for_interrupts: false,
1319 max_deputies: 2,
1320 release_stall_minutes: 60,
1321 }
1322 }
1323}
1324
1325#[derive(Debug, Clone, Deserialize, Serialize)]
1337#[serde(deny_unknown_fields, default)]
1338pub struct Repos {
1339 pub roots: Vec<PathBuf>,
1343 pub scan_ttl: u64,
1350 pub fetch_interval: u64,
1355}
1356
1357impl Default for Repos {
1358 fn default() -> Self {
1359 Self {
1360 roots: Vec::new(),
1361 scan_ttl: 86_400,
1362 fetch_interval: 600,
1363 }
1364 }
1365}
1366
1367#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1383#[serde(deny_unknown_fields, default)]
1384pub struct Prompts {
1385 pub all: String,
1387 pub implement: String,
1389 pub judge: String,
1391 pub review: String,
1393 pub fix: String,
1395}
1396
1397impl Prompts {
1398 pub fn overlay(&self, node: &str) -> Option<String> {
1403 let specific = match node {
1404 "implement" => &self.implement,
1405 "judge" | "vote" | "deliberate" => &self.judge,
1406 "review" => &self.review,
1407 "fix" => &self.fix,
1408 _ => "",
1409 };
1410 let mut parts: Vec<&str> = Vec::new();
1411 for p in [self.all.trim(), specific.trim()] {
1412 if !p.is_empty() {
1413 parts.push(p);
1414 }
1415 }
1416 if parts.is_empty() {
1417 return None;
1418 }
1419 Some(parts.join("\n\n"))
1420 }
1421}
1422
1423#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1430#[serde(deny_unknown_fields, default)]
1431pub struct Notify {
1432 pub command: Vec<String>,
1435}
1436
1437#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1439#[serde(deny_unknown_fields, default)]
1440pub struct Talk {
1441 pub allow_write: bool,
1450 pub personas: Vec<PersonaSpec>,
1455 pub operator_name: Option<String>,
1459}
1460
1461pub const OPERATOR_NAME_MAX: usize = 64;
1463
1464impl Talk {
1465 pub fn operator_name(&self) -> Option<&str> {
1467 self.operator_name
1468 .as_deref()
1469 .map(str::trim)
1470 .filter(|n| !n.is_empty())
1471 }
1472}
1473
1474#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
1476#[serde(deny_unknown_fields)]
1477pub struct PersonaSpec {
1478 pub id: String,
1480 #[serde(default)]
1483 pub name: String,
1484 #[serde(default)]
1487 pub prompt: String,
1488 #[serde(default, skip_serializing_if = "Option::is_none")]
1492 pub icon: Option<String>,
1493}
1494
1495#[derive(Debug, Clone)]
1497pub struct ResolvedRoles {
1498 pub implementers: Vec<AgentSpec>,
1500 pub judges: Vec<AgentSpec>,
1502 pub reviewers: Vec<AgentSpec>,
1504 pub fixer: Option<Vec<AgentSpec>>,
1509 pub conductor: AgentSpec,
1511 pub implementer_roster: Vec<AgentSpec>,
1519 pub judge_roster: Vec<AgentSpec>,
1523 pub reviewer_roster: Vec<AgentSpec>,
1525}
1526
1527fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
1534 let mut out = Vec::new();
1535 for (k, v) in table {
1536 if prefix.is_empty() && k == "vars" {
1537 continue;
1538 }
1539 let path = if prefix.is_empty() {
1540 k.clone()
1541 } else {
1542 format!("{prefix}.{k}")
1543 };
1544 match v {
1545 toml::Value::Array(_) => out.push(path),
1546 toml::Value::Table(t) => out.extend(array_keys(t, &path)),
1547 _ => {}
1548 }
1549 }
1550 out
1551}
1552
1553#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1555enum ArrayMerge {
1556 Append,
1560 Replace,
1563}
1564
1565fn array_merge_policy(key: &str) -> ArrayMerge {
1604 match key {
1605 "verify.e2e" | "verify.gate" | "verify.pre_gate" | "repos.roots" => ArrayMerge::Append,
1606 _ => ArrayMerge::Replace,
1607 }
1608}
1609
1610impl Config {
1611 pub fn load(path: &Path) -> Result<Self> {
1614 Self::load_layers(&[path.to_path_buf()])
1615 }
1616
1617 fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
1627 let mut ctx = teravars::system_context();
1628 let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
1629 ctx.insert("env", &env);
1630 if let Some(last) = paths.last()
1631 && let Some(dir) = last.parent()
1632 {
1633 let dir = std::fs::read_to_string(dir.join(REPO_MARKER))
1636 .map(|s| PathBuf::from(s.trim()))
1637 .unwrap_or_else(|_| dir.to_path_buf());
1638 ctx.insert("repo", &dir.to_string_lossy());
1639 ctx.insert(
1640 "repo_name",
1641 &dir.file_name().unwrap_or_default().to_string_lossy(),
1642 );
1643 }
1644 ctx
1645 }
1646
1647 pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
1655 let mut engine = teravars::Engine::default();
1656 let ctx = Self::render_ctx(paths);
1657 if paths.len() > 1 {
1658 Self::refuse_split_arrays(paths, &mut engine, &ctx).map_err(|error| {
1659 if error.downcast_ref::<ConfigFailure>().is_some() {
1660 error
1661 } else {
1662 let message = error.to_string();
1665 error
1666 .context(ConfigFailure::layers("config-merge", paths))
1667 .context(message)
1668 }
1669 })?;
1670 }
1671 let merged = teravars::load_merged(paths, &mut engine, &ctx)
1672 .map_err(|error| {
1673 let cause = ConfigFailure::render(&error, paths);
1674 anyhow::Error::new(error).context(cause)
1675 })
1676 .with_context(|| {
1677 format!(
1678 "rendering config via teravars: {}",
1679 paths
1680 .iter()
1681 .map(|p| p.display().to_string())
1682 .collect::<Vec<_>>()
1683 .join(", ")
1684 )
1685 })?;
1686 let mut table = merged.config;
1687 Self::normalize_renamed_keys(paths, &mut engine, &ctx, &mut table)?;
1688 table.remove("vars");
1691 let detect_agents = !table.contains_key("agents");
1695 let mut cfg: Self = toml::Value::Table(table)
1696 .try_into()
1697 .context("deserializing magi config")
1698 .context(ConfigFailure::layers("config-deserialize", paths))?;
1699 crate::persona::validate(&cfg.talk.personas)?;
1700 cfg.worktree.validate()?;
1701 if let Some(name) = cfg.talk.operator_name() {
1702 if name.chars().count() > OPERATOR_NAME_MAX || name.chars().any(char::is_control) {
1703 bail!(
1704 "[talk] operator_name must be one line of at most {OPERATOR_NAME_MAX} characters"
1705 );
1706 }
1707 }
1708 if detect_agents {
1709 cfg.agents = Self::autodetected().agents;
1710 }
1711 Ok(cfg)
1712 }
1713
1714 fn normalize_renamed_keys(
1722 paths: &[PathBuf],
1723 engine: &mut teravars::Engine,
1724 ctx: &teravars::Context,
1725 table: &mut toml::map::Map<String, toml::Value>,
1726 ) -> Result<()> {
1727 let both = matches!(
1728 table.get("graph"),
1729 Some(toml::Value::Table(g)) if g.contains_key("candidates") && g.contains_key("implementers")
1730 );
1731 if !both {
1732 return Ok(());
1733 }
1734 let mut winner: Option<toml::Value> = None;
1735 for path in paths {
1736 let one = teravars::load_merged([path], engine, ctx)
1737 .map_err(|error| {
1738 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
1739 anyhow::Error::new(error).context(cause)
1740 })
1741 .with_context(|| format!("rendering {}", path.display()))?;
1742 let Some(toml::Value::Table(g)) = one.config.get("graph") else {
1743 continue;
1744 };
1745 if g.contains_key("candidates") && g.contains_key("implementers") {
1746 bail!(
1747 "`[graph]` sets both `implementers` and its deprecated alias \n `candidates` in {}; keep only `implementers`.",
1748 path.display()
1749 );
1750 }
1751 if let Some(v) = g.get("implementers").or_else(|| g.get("candidates")) {
1752 winner = Some(v.clone());
1753 }
1754 }
1755 if let Some(toml::Value::Table(g)) = table.get_mut("graph") {
1756 g.remove("candidates");
1757 if let Some(v) = winner {
1758 g.insert("implementers".to_owned(), v);
1759 }
1760 }
1761 Ok(())
1762 }
1763
1764 fn refuse_split_arrays(
1788 paths: &[PathBuf],
1789 engine: &mut teravars::Engine,
1790 ctx: &teravars::Context,
1791 ) -> Result<()> {
1792 let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
1793 for path in paths {
1794 let one = teravars::load_merged([path], engine, ctx)
1795 .map_err(|error| {
1796 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
1797 anyhow::Error::new(error).context(cause)
1798 })
1799 .with_context(|| format!("rendering {}", path.display()))?;
1800 for key in array_keys(&one.config, "") {
1801 if array_merge_policy(&key) == ArrayMerge::Append {
1802 continue;
1803 }
1804 if let Some(first) = seen.get(&key) {
1805 bail!(
1806 "`{key}` is an array declared in two config layers:\n \
1807 {}\n {}\nteravars appends arrays when it merges, so \
1808 magi would run the concatenation of both - which is \
1809 not what either file says. Declare `{key}` in exactly \
1810 one of them.",
1811 first.display(),
1812 path.display()
1813 );
1814 }
1815 seen.insert(key, path.clone());
1816 }
1817 }
1818 Ok(())
1819 }
1820
1821 pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
1843 let mut engine = teravars::Engine::default();
1844 let ctx = Self::render_ctx(paths);
1845 let mut out = Vec::new();
1846 for path in paths {
1847 let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
1848 continue;
1849 };
1850 let mut cur = &one.config;
1851 let mut found = None;
1852 let parts: Vec<&str> = key.split('.').collect();
1853 for (i, part) in parts.iter().enumerate() {
1854 match cur.get(*part) {
1855 Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
1856 found = Some(a);
1857 break;
1858 }
1859 Some(toml::Value::Table(t)) => cur = t,
1860 _ => break,
1861 }
1862 }
1863 let Some(values) = found else { continue };
1864 let strings: Vec<String> = values
1865 .iter()
1866 .filter_map(|v| v.as_str().map(str::to_owned))
1867 .collect();
1868 if !strings.is_empty() {
1869 out.push((path.clone(), strings));
1870 }
1871 }
1872 out
1873 }
1874
1875 pub(crate) fn layer_tables(paths: &[PathBuf]) -> Vec<(PathBuf, Result<toml::Table>)> {
1881 let mut engine = teravars::Engine::default();
1882 let ctx = Self::render_ctx(paths);
1883 paths
1884 .iter()
1885 .map(|path| {
1886 let one = teravars::load_merged([path], &mut engine, &ctx)
1887 .map(|m| m.config)
1888 .with_context(|| format!("rendering {}", path.display()));
1889 (path.clone(), one)
1890 })
1891 .collect()
1892 }
1893
1894 pub fn describe_composed(
1904 paths: &[PathBuf],
1905 commands: &[String],
1906 key: &str,
1907 empty: &str,
1908 ) -> String {
1909 if commands.is_empty() {
1910 return empty.to_owned();
1911 }
1912 let joined = commands.join(" && ");
1913 let provenance = Self::array_provenance(paths, key);
1914 if provenance.len() <= 1 {
1915 return joined;
1916 }
1917 let mut out = joined;
1918 for (path, cmds) in &provenance {
1919 out.push_str(&format!("\n [{}] {}", path.display(), cmds.join(" && ")));
1920 }
1921 out
1922 }
1923
1924 pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
1931 #[cfg(test)]
1932 crate::web::request_cost::discovery();
1933 if let Some(p) = explicit {
1934 let paths = vec![p.to_path_buf()];
1935 return Ok((Self::load_layers(&paths)?, paths));
1936 }
1937 let paths = Self::layers_checked(repo)?;
1938 if paths.is_empty() {
1939 return Ok((Self::autodetected(), paths));
1940 }
1941 Ok((Self::load_layers(&paths)?, paths))
1942 }
1943
1944 pub async fn discover_fetched(
1947 repo: &Path,
1948 explicit: Option<&Path>,
1949 ) -> Result<(Self, Vec<PathBuf>)> {
1950 if explicit.is_none() && is_git_worktree(repo) {
1951 let (remote, cfg_base) = probe_remote_base(repo);
1955 let base = crate::git::merge_base_branch(repo, &remote, cfg_base.as_deref())
1956 .await
1957 .with_context(|| ConfigFailure {
1958 stage: "config-base",
1959 target: remote.clone(),
1960 })?;
1961 let out = crate::git::fetch(repo, &remote, &base)
1962 .await
1963 .with_context(|| format!("fetching {remote}/{base} to read magi.toml"))
1964 .with_context(|| ConfigFailure {
1965 stage: "config-fetch",
1966 target: format!("{remote}/{base}"),
1967 })?;
1968 if !out.ok() {
1969 return Err(anyhow::anyhow!(
1970 "cannot read magi.toml: `git fetch {remote} {base}` failed ({}); refusing to use the local checkout's copy, which may be stale",
1971 out.stderr.lines().next().unwrap_or("").trim()
1972 )).context(ConfigFailure { stage: "config-fetch", target: format!("{remote}/{base}") });
1973 }
1974 if cfg_base.is_none() {
1975 crate::git::ensure_remote_head(repo, &remote, &base).await;
1976 }
1977 }
1978 Self::discover(repo, explicit).map_err(|error| {
1979 if error.downcast_ref::<ConfigFailure>().is_some() {
1980 error
1981 } else {
1982 error.context(ConfigFailure {
1983 stage: "config-load",
1984 target: explicit.unwrap_or(repo).to_string_lossy().into_owned(),
1985 })
1986 }
1987 })
1988 }
1989
1990 fn layers_checked(repo: &Path) -> Result<Vec<PathBuf>> {
1992 if !is_git_worktree(repo) {
1993 return Ok(Self::layers(repo));
1994 }
1995 let mut paths: Vec<PathBuf> = Self::machine_layer()
1996 .into_iter()
1997 .filter(|p| p.is_file())
1998 .collect();
1999 paths.extend(Self::repo_layers(repo)?);
2000 Ok(paths)
2001 }
2002
2003 pub(crate) fn repo_layer_description(repo: &Path, path: &Path) -> String {
2005 let cached = path.ancestors().find(|p| p.join(REPO_MARKER).is_file());
2006 if let Some(root) = cached {
2007 let relative = path.strip_prefix(root).unwrap_or(path);
2008 let reference = resolve_remote_base(repo)
2009 .map(|(remote, base)| format!("{remote}/{base}"))
2010 .unwrap_or_else(|_| "remote base".to_owned());
2011 format!(
2012 "{} at {reference} (including its includes)",
2013 repo.join(relative).display()
2014 )
2015 } else {
2016 format!("{} (including its includes)", path.display())
2017 }
2018 }
2019
2020 pub(crate) fn repo_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2023 if !is_git_worktree(repo) {
2024 return Ok([
2025 repo.join(".magi").join("config.toml"),
2026 repo.join("magi.toml"),
2027 ]
2028 .into_iter()
2029 .filter(|p| p.is_file())
2030 .collect());
2031 }
2032 remote_layers(repo)
2033 }
2034
2035 pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
2055
2056 pub fn layers(repo: &Path) -> Vec<PathBuf> {
2061 let mut paths = Vec::new();
2062 paths.extend(Self::machine_layer());
2063 paths.push(repo.join(".magi").join("config.toml"));
2064 paths.push(repo.join("magi.toml"));
2065 paths.retain(|p| p.is_file());
2066 paths
2067 }
2068
2069 #[cfg(test)]
2076 pub(crate) fn machine_layer() -> Option<PathBuf> {
2077 std::env::var(Self::CONFIG_DIR_ENV)
2078 .ok()
2079 .filter(|dir| !dir.trim().is_empty())
2080 .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
2081 }
2082
2083 #[cfg(not(test))]
2085 pub(crate) fn machine_layer() -> Option<PathBuf> {
2086 match std::env::var(Self::CONFIG_DIR_ENV) {
2087 Ok(dir) if dir.trim().is_empty() => None,
2089 Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
2090 Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
2091 }
2092 }
2093
2094 pub fn autodetected() -> Self {
2096 let mut cfg = Self::default();
2097 for (kind, id, model) in [
2098 (AgentKind::Claude, "opus", Some("opus")),
2099 (AgentKind::Claude, "sonnet", Some("sonnet")),
2100 (AgentKind::Antigravity, "antigravity", None),
2101 (AgentKind::Opencode, "opencode", None),
2102 (AgentKind::Codex, "codex", None),
2103 (AgentKind::Omp, "omp", None),
2104 ] {
2105 if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
2106 cfg.agents.push(AgentSpec {
2107 id: id.to_owned(),
2108 kind,
2109 model: model.map(str::to_owned),
2110 command: Vec::new(),
2111 extra_args: Vec::new(),
2112 env: BTreeMap::new(),
2113 prompt_delivery: None,
2114 });
2115 }
2116 }
2117 cfg
2118 }
2119
2120 pub fn cache_dir(&self) -> Option<PathBuf> {
2123 self.verify.cache_dir()
2124 }
2125
2126 pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
2128 self.agents
2129 .iter()
2130 .find(|a| a.id == id)
2131 .with_context(|| format!("no agent with id `{id}` in the roster"))
2132 }
2133
2134 fn rotate(&self, ids: &[String], count: usize, offset: usize) -> Result<Vec<AgentSpec>> {
2141 let mut out = Vec::with_capacity(count);
2142 for i in 0..count {
2143 let spec = if ids.is_empty() {
2144 self.agents[(i + offset) % self.agents.len()].clone()
2145 } else {
2146 self.agent(&ids[i % ids.len()])?.clone()
2147 };
2148 out.push(spec);
2149 }
2150 Ok(out)
2151 }
2152
2153 fn full_roster(&self, ids: &[String]) -> Result<Vec<AgentSpec>> {
2160 if ids.is_empty() {
2161 Ok(self.agents.clone())
2162 } else {
2163 ids.iter().map(|id| self.agent(id).cloned()).collect()
2164 }
2165 }
2166
2167 pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
2174 if self.agents.is_empty() {
2175 bail!(
2176 "agent roster is empty: no agent CLI found on PATH and no \
2177 [[agents]] in the config. Run `magi init` to write a starter \
2178 magi.toml."
2179 );
2180 }
2181 let pinned = self
2182 .graph
2183 .selected_implementer
2184 .as_ref()
2185 .map(|id| self.agent(id).cloned())
2186 .transpose()?;
2187 Ok(ResolvedRoles {
2188 implementers: match &pinned {
2189 Some(agent) => vec![agent.clone()],
2190 None => self.rotate(&self.roles.implementers, self.graph.implementers, 0)?,
2191 },
2192 judges: self.rotate(&self.roles.judges, self.graph.judges, 1)?,
2193 reviewers: self.rotate(&self.roles.reviewers, self.graph.reviewers, 0)?,
2194 fixer: match self.roles.fixer.as_ref() {
2195 Some(choice) => Some(crate::agent::pick_chain(
2198 &self.agents,
2199 Some(choice),
2200 &|_| true,
2201 "fixer",
2202 )?),
2203 None => None,
2204 },
2205 conductor: match self.roles.conductor.as_ref().map(AgentChoice::ids) {
2210 Some(ids) if ids.len() == 1 => self.agent(ids[0])?.clone(),
2211 Some(ids) if !ids.is_empty() => ids
2214 .iter()
2215 .find_map(|id| self.agent(id).ok())
2216 .cloned()
2217 .with_context(|| {
2218 format!("[roles] conductor names no agent in the roster: {ids:?}")
2219 })?,
2220 _ => crate::agent::pick(&self.agents, None, &crate::agent::installed)
2225 .unwrap_or_else(|_| self.agents[0].clone()),
2226 },
2227 implementer_roster: match pinned {
2228 Some(agent) => vec![agent],
2229 None => self.full_roster(&self.roles.implementers)?,
2230 },
2231 judge_roster: self.full_roster(&self.roles.judges)?,
2232 reviewer_roster: self.full_roster(&self.roles.reviewers)?,
2233 })
2234 }
2235
2236 pub fn advisors(&self) -> Result<Vec<AgentSpec>> {
2258 if self.agents.is_empty() {
2259 bail!(
2260 "agent roster is empty: no agent CLI found on PATH and no \
2261 [[agents]] in the config. Run `magi init` to write a starter \
2262 magi.toml."
2263 );
2264 }
2265 if !self.roles.advisors.is_empty() {
2266 return self.rotate(&self.roles.advisors, self.graph.advisors, 0);
2267 }
2268 self.rotate(&self.roles.judges, self.graph.advisors, 1)
2269 }
2270
2271 pub fn advisor_roster(&self) -> Result<Vec<AgentSpec>> {
2275 if self.roles.advisors.is_empty() {
2276 self.full_roster(&self.roles.judges)
2277 } else {
2278 self.full_roster(&self.roles.advisors)
2279 }
2280 }
2281
2282 pub fn shell(&self) -> Vec<String> {
2284 if let Some(s) = &self.verify.shell {
2285 return s.clone();
2286 }
2287 if which("sh") {
2288 vec!["sh".to_owned(), "-c".to_owned()]
2289 } else {
2290 vec!["cmd".to_owned(), "/C".to_owned()]
2291 }
2292 }
2293
2294 pub fn starter_toml() -> String {
2296 let detected = Self::autodetected();
2297 let mut s = String::from(
2298 "# magi — blind multi-agent implementation competition.\n\
2299 # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
2300 # -> blind judging -> deliberation -> private final vote\n\
2301 # -> fold losers -> review + E2E loop -> gate -> merge.\n\
2302 #\n\
2303 # Rendered by teravars: a `[vars]` table, env\n\
2304 # and system lookups, and `include = [...]` all work. Tera\n\
2305 # braces are live everywhere in this file, but comments are\n\
2306 # stripped before rendering (teravars >= 0.2.2), so a comment\n\
2307 # may quote `{{ ... }}` freely.\n\
2308 #\n\
2309 # Layers deep-merge in increasing\n\
2310 # precedence, so the roster can live once per machine in\n\
2311 # <config_dir>/magi/config.toml and each repo only states its own\n\
2312 # gate:\n\
2313 # <config_dir>/magi/config.toml < .magi/config.toml < magi.toml\n\n\
2314 [vars]\n\
2315 # Reference it as vars.cache inside Tera braces, anywhere below.\n\
2316 # Single quotes inside the braces: teravars renders the raw file\n\
2317 # text, so TOML's own \\\" escaping never reaches Tera.\n\
2318 cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
2319 );
2320 if detected.agents.is_empty() {
2321 s.push_str(
2322 "# No agent CLI was found on PATH. Fill this in by hand.\n\
2323 # kind = claude | opencode | antigravity | codex | command\n\
2324 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
2325 );
2326 } else {
2327 for a in &detected.agents {
2328 s.push_str("[[agents]]\n");
2329 s.push_str(&format!("id = {:?}\n", a.id));
2330 s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
2331 if let Some(m) = &a.model {
2332 s.push_str(&format!("model = {m:?}\n"));
2333 }
2334 s.push('\n');
2335 }
2336 }
2337 s.push_str(
2338 "# Leave a role list empty to rotate through the roster.\n\
2339 # A non-empty list is also an ordered backup list: seats take entries from the\n\
2340 # front (see [graph] counts) and a failed or out-of-quota seat moves on to the\n\
2341 # next agent to its right, each tried once. Same for judges and reviewers.\n\
2342 # implementers = [\"opus\", \"codex\", \"sonnet\"] # with implementers = 1 below: opus sits, codex then sonnet are spares\n\
2343 [roles]\n\
2344 implementers = []\n\
2345 judges = []\n\
2346 reviewers = []\n\
2347 # conductor = \"opus\" # arranges the queue; unset picks a seat like chatter does\n\
2348 # synthesizer = \"opus\" # blends the advisors into one brief; unset picks a seat like chatter does\n\
2349 # synthesizer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\
2350 # language_judge = \"jev\" # kind = \"command\" wrapper deciding if PR text is English; unset keeps the built-in heuristics\n\
2351 # dupes_judge = \"opus\" # judges duplicate-work claims; unset inherits chatter (string or fallback chain)\n\
2352 # fixer = \"opus\" # applies review findings; unset keeps the winner's own author\n\
2353 # fixer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\n\
2354 [graph]\n\
2355 # Gate GitHub prose; secret redaction is always enabled.\n\
2356 github_text_guard = true\n\
2357 # Language of PR / issue titles, bodies and comments; non-English drops the English-only check (commits stay English).\n\
2358 github_language = \"en\"\n\
2359 implementers = 3\n\
2360 judges = 3\n\
2361 deliberate_rounds = 1\n\
2362 reviewers = 3\n\
2363 review_rounds = 6\n\
2364 # Fix rounds a failing verify.gate gets before the run is blocked (0 = none).\n\
2365 gate_fix_rounds = 1\n\
2366 # Rerun a failed required CI check once before a land fix round (flaky tests).\n\
2367 rerun_flaky_checks = true\n\
2368 # Port the strengths judges named in the losing candidates onto the\n\
2369 # winner before review (best-effort; rolled back on failure or a big diff).\n\
2370 graft_runner_up = true\n\
2371 max_parallel = 4\n\
2372 language = \"en\"\n\
2373 # One CLI conversation per seat: judges keep their own argument\n\
2374 # across deliberation, the fixer keeps its implementation context.\n\
2375 sessions = true\n\
2376 # Reviewer-seat timeout. When timeout_verify is omitted, E2E and\n\
2377 # the final gate inherit this value for compatibility.\n\
2378 timeout_review = 1200\n\
2379 # Optional independent E2E/final-gate timeout; uncomment to keep\n\
2380 # verification independent if timeout_review changes later.\n\
2381 # timeout_verify = 1200\n\
2382 # Longest a seat waits for the shared build cache before it is\n\
2383 # spawned. Never counted against an agent's own timeout; expiry\n\
2384 # holds the run (resumable) instead of failing the agent.\n\
2385 # timeout_resource_wait = 1800\n\n\
2386 # What the chat calls you (persona address and the Chat's turn label).\n\
2387 # [talk]\n\
2388 # operator_name = \"Commander\"\n\n\
2389 # Chat personas (tone only; the web Chat picks one per conversation).\n\
2390 # Built in: magi, rei, misato, ritsuko, shinji, asuka, kaworu. Entries add to\n\
2391 # them, and one with a built-in's id replaces it. `default` is the plain\n\
2392 # voice and cannot be redefined (it may only set `icon`). Declare this in one\n\
2393 # layer only. `icon` is an optional avatar, display only: an absolute or\n\
2394 # ~/ path to a png/jpg/gif/webp, or a data:image/...;base64 URI, up to\n\
2395 # 256 KiB; a missing or bad one falls back to the built-in avatar.\n\
2396 # [[talk.personas]]\n\
2397 # id = \"gendo\"\n\
2398 # name = \"Gendo Ikari\"\n\
2399 # prompt = \"Speak coldly and tersely, hands folded.\"\n\
2400 # icon = \"~/pictures/gendo.png\"\n\n\
2401 [verify]\n\
2402 # Run once per review round in the winner's worktree; failures are\n\
2403 # fed back to the fixer.\n\
2404 e2e = []\n\
2405 # Final gate. Every command must exit 0 before a merge.\n\
2406 gate = []\n\
2407 # Mechanical fixers (formatters) run in the winner's worktree just\n\
2408 # before the gate; whatever they change becomes one commit. A failing\n\
2409 # command only warns - the gate stays the arbiter. Same timeout as the\n\
2410 # gate (timeout_verify). Keep it light and idempotent.\n\
2411 # pre_gate = []\n\n\
2412 # Prepare each worktree magi creates (candidates, judges, advisors,\n\
2413 # reviewers, the operator-fix and review-takeover checkouts), in order,\n\
2414 # before any agent or verify command touches it. `copy` reads from the\n\
2415 # primary checkout and never overwrites; `optional` skips a missing\n\
2416 # source. `run` goes through the shell with the worktree as cwd and\n\
2417 # fails the seat on a non-zero exit or timeout (timeout_secs, default\n\
2418 # the verify timeout). Setup must not edit tracked files, and what it\n\
2419 # leaves untracked is kept out of magi's commits. Declare this in one\n\
2420 # layer only.\n\
2421 # [worktree]\n\
2422 # setup = [\n\
2423 # { copy = \".env.example -> .env\" },\n\
2424 # { copy = \".env.local\", optional = true },\n\
2425 # { run = \"pnpm install --frozen-lockfile\", timeout_secs = 900 },\n\
2426 # ]\n\n\
2427 [merge]\n\
2428 # none | local | pr\n\
2429 mode = \"none\"\n\
2430 # release_bump = true # Rust (Cargo.toml) repositories only; a no-op elsewhere\n\n\
2431 [update]\n\
2432 # off | notify | install — checked in the background, throttled.\n\
2433 mode = \"notify\"\n\
2434 # interval = \"24h\"\n\n\
2435 [daemon]\n\
2436 # Minutes a release-bump pull request (chore/release-v*) may sit with\n\
2437 # no new commit and no check changing state before `magi serve`\n\
2438 # notices and asks you. A failed check is rerun once on its own;\n\
2439 # still red after that escalates at once. 0 turns the watcher off.\n\
2440 # release_stall_minutes = 60\n\n\
2441 [release]\n\
2442 # actions (default) | local. \"local\" is for repositories whose GitHub\n\
2443 # Actions never run (private, no minutes): the release pull request\n\
2444 # does not wait for CI, you approve the merge in magi, and then\n\
2445 # `magi serve` pushes the vX.Y.Z tag (never over an existing one) and\n\
2446 # runs `commands` from a clean checkout of the merge commit. A\n\
2447 # failure holds the release with a notice; it is never retried blind.\n\
2448 # Needs `magi serve` running and [daemon] release_stall_minutes > 0.\n\
2449 # mode = \"actions\"\n\
2450 # Run in order; the first failure stops. They see MAGI_RELEASE_VERSION,\n\
2451 # MAGI_RELEASE_TAG, MAGI_RELEASE_COMMIT and MAGI_RELEASE_PR. Make them\n\
2452 # safe to repeat: a crash mid-command is treated as unfinished.\n\
2453 # commands = [\"cargo build --release\", \"gh release create \\\"$MAGI_RELEASE_TAG\\\" --generate-notes\"]\n\
2454 # timeout_minutes = 30\n",
2455 );
2456 s
2457 }
2458}
2459
2460pub fn which(program: &str) -> bool {
2462 find_program(program).is_some()
2463}
2464
2465pub fn find_program(program: &str) -> Option<PathBuf> {
2474 find_program_on(program, &std::env::var_os("PATH")?)
2475}
2476
2477pub fn find_program_on(program: &str, paths: &std::ffi::OsStr) -> Option<PathBuf> {
2480 let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".EXE;.CMD;.BAT".into());
2481 find_program_in(program, paths, cfg!(windows).then_some(pathext.as_str()))
2482}
2483
2484fn find_program_in(
2485 program: &str,
2486 paths: &std::ffi::OsStr,
2487 pathext: Option<&str>,
2488) -> Option<PathBuf> {
2489 let p = Path::new(program);
2490 if p.components().count() > 1 {
2491 return p.is_file().then(|| p.to_path_buf());
2492 }
2493 std::env::split_paths(paths).find_map(|dir| match pathext {
2494 Some(exts) => {
2495 let bare = dir.join(program);
2496 if p.extension().is_some() && bare.is_file() {
2497 return Some(bare);
2498 }
2499 exts.split(';')
2500 .filter(|e| !e.is_empty())
2501 .map(|e| dir.join(format!("{program}{}", e.to_lowercase())))
2502 .find(|c| c.is_file())
2503 }
2504 None => Some(dir.join(program)).filter(|c| c.is_file()),
2505 })
2506}
2507
2508const REPO_MARKER: &str = ".magi-repo";
2510
2511fn git_out(repo: &Path, args: &[&str]) -> Option<String> {
2512 use crate::proc::Quiet as _;
2513 #[cfg(test)]
2514 crate::web::request_cost::git();
2515 let out = std::process::Command::new("git")
2516 .args(args)
2517 .quiet()
2518 .current_dir(repo)
2519 .stdin(std::process::Stdio::null())
2520 .output()
2521 .ok()?;
2522 out.status
2523 .success()
2524 .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
2525}
2526
2527fn is_git_worktree(repo: &Path) -> bool {
2530 git_out(repo, &["rev-parse", "--git-dir"]).is_some()
2531}
2532
2533#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2536pub enum OwnerHold {
2537 LandApproval,
2539 HoldContestedMerge,
2541}
2542
2543impl OwnerHold {
2544 pub const ALL: [Self; 2] = [Self::LandApproval, Self::HoldContestedMerge];
2546
2547 pub fn key(self) -> &'static str {
2549 match self {
2550 Self::LandApproval => "land_approval",
2551 Self::HoldContestedMerge => "hold_contested_merge",
2552 }
2553 }
2554
2555 pub fn base_value(self, graph: &Graph) -> bool {
2557 match self {
2558 Self::LandApproval => graph.land_approval,
2559 Self::HoldContestedMerge => graph.hold_contested_merge,
2560 }
2561 }
2562}
2563
2564pub async fn branch_owner_holds(
2567 repo: &Path,
2568 head: &str,
2569) -> (Vec<(OwnerHold, String)>, Vec<String>) {
2570 let mut holds = Vec::new();
2571 let mut diagnostics = Vec::new();
2572 if let Err(error) =
2575 crate::git::git(repo, &["cat-file", "-e", &format!("{head}^{{commit}}")]).await
2576 {
2577 diagnostics.push(format!("cannot read reviewed commit {head}: {error:#}"));
2578 return (holds, diagnostics);
2579 }
2580 for file in ["magi.toml", ".magi/config.toml"] {
2581 let object = format!("{head}:{file}");
2582 let text = match crate::git::git(repo, &["show", &object]).await {
2583 Ok(text) => text,
2584 Err(error) => {
2585 let error = format!("{error:#}");
2587 if !error.contains("does not exist in")
2588 && !error.contains("exists on disk, but not in")
2589 {
2590 diagnostics.push(format!(
2591 "cannot read reviewed branch {file} at {head}: {error}"
2592 ));
2593 }
2594 continue;
2595 }
2596 };
2597 let value = match toml::from_str::<toml::Value>(&text) {
2598 Ok(value) => value,
2599 Err(error) => {
2600 diagnostics.push(format!(
2601 "cannot parse reviewed branch {file} at {head}: {error}"
2602 ));
2603 continue;
2604 }
2605 };
2606 if value.get("include").is_some() || text.contains("{{") || text.contains("{%") {
2607 diagnostics.push(format!("reviewed branch {file} at {head}: only literal owner holds are read; includes and templates are ignored"));
2608 }
2609 for hold in OwnerHold::ALL {
2610 if value
2611 .get("graph")
2612 .and_then(|g| g.get(hold.key()))
2613 .and_then(toml::Value::as_bool)
2614 == Some(true)
2615 {
2616 holds.push((hold, file.to_owned()));
2617 }
2618 }
2619 }
2620 (holds, diagnostics)
2621}
2622
2623#[derive(Deserialize, Default)]
2624struct ProbeMerge {
2625 base: Option<String>,
2626 remote: Option<String>,
2627}
2628
2629#[derive(Deserialize, Default)]
2630struct Probe {
2631 merge: Option<ProbeMerge>,
2632}
2633
2634fn probe_merge(path: &Path, repo: &Path) -> Option<ProbeMerge> {
2640 if !path.is_file() {
2641 return None;
2642 }
2643 let paths = [path.to_path_buf()];
2644 let mut engine = teravars::Engine::default();
2645 let mut ctx = Config::render_ctx(&paths);
2646 ctx.insert("repo", &repo.to_string_lossy());
2649 ctx.insert(
2650 "repo_name",
2651 &repo.file_name().unwrap_or_default().to_string_lossy(),
2652 );
2653 if let Ok(merged) = teravars::load_merged(&paths, &mut engine, &ctx)
2654 && let Ok(probe) = toml::Value::Table(merged.config).try_into::<Probe>()
2655 {
2656 return probe.merge;
2657 }
2658 let text = std::fs::read_to_string(path).ok()?;
2659 toml::from_str::<Probe>(&text).ok()?.merge
2660}
2661
2662fn probe_remote_base(repo: &Path) -> (String, Option<String>) {
2664 let mut remote = None;
2665 let mut base = None;
2666 let mut sources: Vec<PathBuf> = Config::machine_layer().into_iter().collect();
2667 sources.push(repo.join("magi.toml"));
2668 sources.push(repo.join(".magi").join("config.toml"));
2669 for path in sources {
2670 if let Some(m) = probe_merge(&path, repo) {
2671 remote = remote.or(m.remote.filter(|s| !s.trim().is_empty()));
2672 base = base.or(m.base.filter(|s| !s.trim().is_empty()));
2673 }
2674 }
2675 (remote.unwrap_or_else(|| "origin".to_owned()), base)
2676}
2677
2678fn resolve_remote_base(repo: &Path) -> Result<(String, String)> {
2680 let (remote, base) = probe_remote_base(repo);
2681 let base = match base {
2682 Some(b) => b,
2683 None => {
2684 let head = format!("refs/remotes/{remote}/HEAD");
2685 git_out(repo, &["symbolic-ref", "--quiet", &head])
2686 .and_then(|s| crate::git::remote_head_branch(&remote, &s))
2687 .with_context(|| {
2688 format!(
2689 "cannot tell which branch of `{remote}` holds magi.toml: \
2690 set [merge] base, or run `git remote set-head {remote} -a`"
2691 )
2692 })?
2693 }
2694 };
2695 Ok((remote, base))
2696}
2697
2698fn fnv_hex(text: &str) -> String {
2699 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
2700 for b in text.bytes() {
2701 hash ^= u64::from(b);
2702 hash = hash.wrapping_mul(0x0100_0000_01b3);
2703 }
2704 format!("{hash:016x}")
2705}
2706
2707fn declares_include(text: &str) -> bool {
2713 match toml::from_str::<toml::Table>(text) {
2714 Ok(table) => {
2715 table.contains_key("include")
2716 || table
2717 .get("teravars")
2718 .and_then(toml::Value::as_table)
2719 .is_some_and(|t| t.contains_key("include"))
2720 }
2721 Err(_) => text.contains("include"),
2722 }
2723}
2724
2725fn extract_tree(repo: &Path, sha: &str, dest: &Path) -> Result<()> {
2728 use crate::proc::Quiet as _;
2729 #[cfg(test)]
2730 crate::web::request_cost::git();
2731 let mut archive = std::process::Command::new("git")
2732 .args(["archive", "--format=tar", sha])
2733 .quiet()
2734 .current_dir(repo)
2735 .stdin(std::process::Stdio::null())
2736 .stdout(std::process::Stdio::piped())
2737 .stderr(std::process::Stdio::null())
2738 .spawn()
2739 .context("running git archive")?;
2740 let tar = std::process::Command::new("tar")
2741 .arg("-x")
2742 .arg("-C")
2743 .arg(dest)
2744 .quiet()
2745 .stdin(archive.stdout.take().context("git archive has no stdout")?)
2746 .output()
2747 .context("running tar")?;
2748 let status = archive.wait().context("waiting for git archive")?;
2749 if !status.success() || !tar.status.success() {
2750 bail!(
2751 "cannot unpack {sha} for the config's includes: {}",
2752 String::from_utf8_lossy(&tar.stderr).trim()
2753 );
2754 }
2755 Ok(())
2756}
2757
2758fn remote_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2761 let (remote, base) = resolve_remote_base(repo)?;
2762 let tracking = format!("refs/remotes/{remote}/{base}");
2763 let spec = format!("{tracking}^{{commit}}");
2764 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
2765 .map(|s| s.trim().to_owned())
2766 .filter(|s| !s.is_empty())
2767 .with_context(|| {
2768 format!(
2769 "`{remote}/{base}` does not exist in this checkout; fetch it \
2770 (`git fetch {remote} {base}`) or set [merge] base/remote. magi will not read \
2771 a possibly stale local magi.toml instead"
2772 )
2773 })?;
2774 let key = format!("{sha}-{}", fnv_hex(&repo.to_string_lossy()));
2775 let rels = [".magi/config.toml", "magi.toml"];
2776 let mut texts: Vec<(&str, String)> = Vec::new();
2777 for rel in rels {
2778 let object = format!("{sha}:{rel}");
2779 if git_out(repo, &["cat-file", "-e", &object]).is_none() {
2780 continue;
2781 }
2782 let Some(text) = git_out(repo, &["show", &object]) else {
2783 bail!("cannot read {rel} from {remote}/{base} ({sha})");
2784 };
2785 texts.push((rel, text));
2786 }
2787 let wants_tree = texts.iter().any(|(_, t)| declares_include(t));
2788 let build = |root: &Path| -> Result<PathBuf> {
2792 let final_dir = root.join(&key);
2793 if !final_dir.is_dir() {
2794 std::fs::create_dir_all(root)?;
2795 let tmp = root.join(format!(
2796 "{key}.tmp-{}-{}",
2797 std::process::id(),
2798 std::time::SystemTime::now()
2799 .duration_since(std::time::UNIX_EPOCH)
2800 .map(|d| d.as_nanos())
2801 .unwrap_or_default()
2802 ));
2803 let filled = (|| -> Result<()> {
2804 std::fs::create_dir_all(&tmp)?;
2805 if wants_tree {
2806 extract_tree(repo, &sha, &tmp)?;
2807 }
2808 for (rel, text) in &texts {
2809 let file = tmp.join(rel);
2810 let parent = file.parent().unwrap_or(&tmp);
2811 std::fs::create_dir_all(parent)?;
2812 std::fs::write(&file, text)?;
2813 std::fs::write(parent.join(REPO_MARKER), repo.to_string_lossy().as_bytes())?;
2814 }
2815 Ok(())
2816 })();
2817 if let Err(e) = filled {
2818 let _ = std::fs::remove_dir_all(&tmp);
2819 return Err(e);
2820 }
2821 if std::fs::rename(&tmp, &final_dir).is_err() {
2822 let _ = std::fs::remove_dir_all(&tmp);
2824 if !final_dir.is_dir() {
2825 bail!("cannot place {}", final_dir.display());
2826 }
2827 }
2828 }
2829 Ok(final_dir)
2830 };
2831 let common = git_out(
2832 repo,
2833 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
2834 )
2835 .map(|s| PathBuf::from(s.trim()).join("magi").join("config"));
2836 let dir = match common.map(|c| build(&c)) {
2837 Some(Ok(d)) => d,
2838 _ => build(&std::env::temp_dir().join("magi-config"))
2839 .with_context(|| format!("extracting config from {remote}/{base}"))?,
2840 };
2841 Ok(texts.iter().map(|(rel, _)| dir.join(rel)).collect())
2842}
2843
2844#[cfg(test)]
2845mod tests {
2846 #[test]
2847 fn coordination_defaults_off_and_validates_rendered_layer_values() {
2848 let dir = tempfile::tempdir().unwrap();
2849 let machine = dir.path().join("machine.toml");
2850 let repo = dir.path().join("repo.toml");
2851 std::fs::write(&machine, "").unwrap();
2852 assert!(Config::default().coordination.is_none());
2853 assert!(Config::load(&machine).unwrap().coordination.is_none());
2854 std::fs::write(
2855 &machine,
2856 r#"
2857[vars]
2858contract = "updater.contract"
2859[coordination]
2860contract_file = "{{ vars.contract }}"
2861contract_token = "protocol-v1"
2862lock_file = "updater.lock"
2863"#,
2864 )
2865 .unwrap();
2866 let cfg = Config::load(&machine).unwrap();
2867 let policy = cfg.coordination.unwrap();
2868 assert_eq!(policy.contract_file, "updater.contract");
2869 assert_eq!(policy.contract_token, "protocol-v1");
2870 assert_eq!(policy.lock_file, "updater.lock");
2871 std::fs::write(&repo, "[coordination]\nlock_file = 'repository.lock'\n").unwrap();
2872 let cfg = Config::load_layers(&[machine.clone(), repo.clone()]).unwrap();
2873 let policy = cfg.coordination.unwrap();
2874 assert_eq!(policy.contract_file, "updater.contract");
2875 assert_eq!(policy.lock_file, "repository.lock");
2876 std::fs::write(
2877 &repo,
2878 r#"
2879[vars]
2880bad = "../escape"
2881[coordination]
2882lock_file = "{{ vars.bad }}"
2883"#,
2884 )
2885 .unwrap();
2886 let error = Config::load_layers(&[machine, repo]).unwrap_err();
2887 assert!(format!("{error:#}").contains("coordination.lock_file"));
2888 }
2889
2890 #[test]
2891 fn coordination_rejects_invalid_names_tokens_and_incomplete_sections() {
2892 let dir = tempfile::tempdir().unwrap();
2893 let path = dir.path().join("config.toml");
2894 let valid = toml::toml! {
2895 [coordination]
2896 contract_file = "updater.contract"
2897 contract_token = "protocol-v1"
2898 lock_file = "updater.lock"
2899 };
2900 for key in ["contract_file", "lock_file"] {
2901 for bad in [
2902 "",
2903 " ",
2904 " file",
2905 "file ",
2906 "\tfile",
2907 "file\t",
2908 ".",
2909 "..",
2910 "file..name",
2911 "../escape",
2912 "a/b",
2913 "a\\b",
2914 "/absolute",
2915 "C:drive",
2916 "C:\\absolute",
2917 "nul\0name",
2918 ] {
2919 let mut table = valid.clone();
2920 table["coordination"][key] = bad.into();
2921 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
2922 let error = Config::load(&path).unwrap_err();
2923 assert!(
2924 format!("{error:#}").contains(&format!("coordination.{key}")),
2925 "{bad:?}: {error:#}"
2926 );
2927 }
2928 }
2929 for bad in ["", " ", " token", "token ", "two\nlines", "two\rlines"] {
2930 let mut table = valid.clone();
2931 table["coordination"]["contract_token"] = bad.into();
2932 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
2933 let error = Config::load(&path).unwrap_err();
2934 assert!(
2935 format!("{error:#}").contains("coordination.contract_token"),
2936 "{error:#}"
2937 );
2938 }
2939 for key in ["contract_file", "contract_token", "lock_file"] {
2940 let mut table = valid.clone();
2941 table["coordination"].as_table_mut().unwrap().remove(key);
2942 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
2943 let error = Config::load(&path).unwrap_err();
2944 assert!(
2945 format!("{error:#}").contains(&format!("coordination.{key}")),
2946 "{error:#}"
2947 );
2948 }
2949 let mut table = valid;
2950 table["coordination"]
2951 .as_table_mut()
2952 .unwrap()
2953 .insert("typo".into(), "value".into());
2954 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
2955 assert!(format!("{:#}", Config::load(&path).unwrap_err()).contains("typo"));
2956 }
2957
2958 #[test]
2959 fn context_window_prefers_exact_then_longest_prefix_and_user_over_builtin() {
2960 let mut cfg = Config::default();
2961 assert_eq!(
2962 cfg.context_window("claude-sonnet-4-5-20250929"),
2963 Some(200_000)
2964 );
2965 assert_eq!(cfg.context_window("gpt-4.1-mini"), Some(1_000_000));
2966 assert_eq!(cfg.context_window("mystery-model"), None);
2967 cfg.context_windows
2968 .insert("claude-sonnet-4-5".into(), 1_000_000);
2969 cfg.context_windows.insert("claude-sonnet-4".into(), 5);
2970 cfg.context_windows.insert("mystery".into(), 32_768);
2971 assert_eq!(
2973 cfg.context_window("claude-sonnet-4-5-20250929"),
2974 Some(1_000_000)
2975 );
2976 cfg.context_windows
2978 .insert("claude-sonnet-4-5-20250929".into(), 7);
2979 assert_eq!(cfg.context_window("claude-sonnet-4-5-20250929"), Some(7));
2980 assert_eq!(cfg.context_window("mystery-model"), Some(32_768));
2981 }
2982
2983 use super::*;
2984
2985 #[test]
2988 fn windows_lookup_picks_the_cmd_shim_over_the_extensionless_script() {
2989 let dir = tempfile::tempdir().unwrap();
2990 std::fs::write(dir.path().join("codex"), "#!/bin/sh\n").unwrap();
2991 std::fs::write(dir.path().join("codex.cmd"), "@echo off\n").unwrap();
2992 let paths = dir.path().as_os_str();
2993 assert_eq!(
2994 find_program_in("codex", paths, Some(".EXE;.CMD")),
2995 Some(dir.path().join("codex.cmd"))
2996 );
2997 assert_eq!(
2998 find_program_in("codex", paths, None),
2999 Some(dir.path().join("codex"))
3000 );
3001 assert_eq!(find_program_in("claude", paths, Some(".EXE;.CMD")), None);
3002 }
3003
3004 fn spec(id: &str) -> AgentSpec {
3005 AgentSpec {
3006 id: id.to_owned(),
3007 kind: AgentKind::Command,
3008 model: None,
3009 command: vec!["true".to_owned()],
3010 extra_args: Vec::new(),
3011 env: BTreeMap::new(),
3012 prompt_delivery: None,
3013 }
3014 }
3015
3016 #[test]
3017 fn github_text_guard_defaults_on_and_can_be_disabled() {
3018 let default: Graph = toml::from_str("").unwrap();
3019 assert!(default.github_text_guard);
3020 let disabled: Graph = toml::from_str("github_text_guard = false").unwrap();
3021 assert!(!disabled.github_text_guard);
3022 let config = layered("", "[graph]\ngithub_text_guard = false\n").unwrap();
3023 assert!(!config.graph.github_text_guard);
3024 assert!(Config::starter_toml().contains("github_text_guard = true"));
3025 }
3026
3027 #[test]
3028 fn rerun_flaky_checks_defaults_on_and_is_in_the_starter() {
3029 assert!(Graph::default().rerun_flaky_checks);
3030 let off: Graph = toml::from_str("rerun_flaky_checks = false").unwrap();
3031 assert!(!off.rerun_flaky_checks);
3032 assert!(Config::starter_toml().contains("rerun_flaky_checks = true"));
3033 }
3034
3035 #[test]
3036 fn timeout_verify_omitted_from_old_toml_inherits_timeout_review() {
3037 let g: Graph = toml::from_str("timeout_review = 3600").expect("parse");
3042 assert_eq!(g.timeout_verify, None);
3043 assert_eq!(g.verify_timeout(), 3600);
3044 }
3045
3046 #[test]
3047 fn shrinking_timeout_review_does_not_shrink_timeout_verify() {
3048 let g: Graph = toml::from_str("timeout_review = 45").expect("parse");
3053 assert_eq!(g.timeout_review, 45);
3054 assert_eq!(
3055 g.verify_timeout(),
3056 45,
3057 "an omitted legacy value follows review"
3058 );
3059 let explicit: Graph = toml::from_str("timeout_review = 45\ntimeout_verify = 1200")
3060 .expect("parse explicit override");
3061 assert_eq!(explicit.verify_timeout(), 1200);
3062 }
3063
3064 #[test]
3065 fn graph_implementers_new_key_loads_and_old_key_is_an_alias() {
3066 let g: Graph = toml::from_str("implementers = 4\n").unwrap();
3067 assert_eq!(g.implementers, 4);
3068 let g: Graph = toml::from_str("candidates = 5\n").unwrap();
3069 assert_eq!(g.implementers, 5);
3070 }
3071
3072 fn layered(lower: &str, upper: &str) -> Result<Config> {
3073 let dir = tempfile::tempdir().unwrap();
3074 let a = dir.path().join("a.toml");
3075 let b = dir.path().join("b.toml");
3076 std::fs::write(&a, lower).unwrap();
3077 std::fs::write(&b, upper).unwrap();
3078 Config::load_layers(&[a, b])
3079 }
3080
3081 #[test]
3082 fn graph_implementers_higher_layer_wins_across_spellings() {
3083 let c = layered("[graph]\ncandidates = 2\n", "[graph]\nimplementers = 5\n").unwrap();
3084 assert_eq!(c.graph.implementers, 5);
3085 let c = layered("[graph]\nimplementers = 2\n", "[graph]\ncandidates = 5\n").unwrap();
3086 assert_eq!(c.graph.implementers, 5);
3087 let c = layered("[graph]\ncandidates = 2\n", "[graph]\njudges = 3\n").unwrap();
3088 assert_eq!(c.graph.implementers, 2);
3089 }
3090
3091 #[test]
3092 fn graph_implementers_both_keys_in_one_layer_is_refused() {
3093 let err = layered("", "[graph]\ncandidates = 2\nimplementers = 3\n")
3094 .unwrap_err()
3095 .to_string();
3096 assert!(
3097 err.contains("candidates") && err.contains("implementers"),
3098 "{err}"
3099 );
3100 assert!(err.contains("b.toml"), "{err}");
3101 }
3102
3103 #[test]
3104 fn a_toml_layer_written_before_these_fields_existed_still_parses() {
3105 let g: Graph =
3109 toml::from_str("candidates = 1\nreviewers = 3\nreview_rounds = 6\nmax_parallel = 4\n")
3110 .expect("an old-shaped [graph] table must still parse");
3111 assert_eq!(g.verify_timeout(), Graph::default().timeout_review);
3112 assert!(
3113 !g.e2e_every_round,
3114 "off by default, same as before this field existed"
3115 );
3116 }
3117
3118 #[test]
3119 fn empty_roles_rotate_judges_off_their_own_candidate() {
3120 let cfg = Config {
3123 agents: vec![spec("a"), spec("b"), spec("c")],
3124 graph: Graph {
3125 implementers: 3,
3126 ..Graph::default()
3127 },
3128 ..Config::default()
3129 };
3130 let roles = cfg.resolve_roles().unwrap();
3131 let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
3132 let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
3133 assert_eq!(impls, ["a", "b", "c"]);
3134 assert_eq!(judges, ["b", "c", "a"]);
3135 for (i, j) in judges.iter().enumerate() {
3136 assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
3137 }
3138 }
3139
3140 #[test]
3141 fn single_agent_roster_fills_every_seat() {
3142 let cfg = Config {
3143 agents: vec![spec("solo")],
3144 graph: Graph {
3145 implementers: 3,
3146 ..Graph::default()
3147 },
3148 ..Config::default()
3149 };
3150 let roles = cfg.resolve_roles().unwrap();
3151 assert_eq!(roles.implementers.len(), 3);
3152 assert!(roles.judges.iter().all(|a| a.id == "solo"));
3153 }
3154
3155 #[test]
3156 fn implementer_roster_is_the_whole_agent_list_untruncated_when_unset() {
3157 let cfg = Config {
3162 agents: vec![spec("a"), spec("b"), spec("c")],
3163 graph: Graph {
3164 implementers: 1,
3165 ..Graph::default()
3166 },
3167 ..Config::default()
3168 };
3169 let roles = cfg.resolve_roles().unwrap();
3170 assert_eq!(roles.implementers.len(), 1);
3171 let roster: Vec<&str> = roles
3172 .implementer_roster
3173 .iter()
3174 .map(|a| a.id.as_str())
3175 .collect();
3176 assert_eq!(roster, ["a", "b", "c"]);
3177 }
3178
3179 #[test]
3180 fn implementer_roster_follows_explicit_ids_in_the_order_named() {
3181 let cfg = Config {
3182 agents: vec![spec("a"), spec("b"), spec("c")],
3183 roles: Roles {
3184 implementers: vec!["c".to_owned(), "a".to_owned()],
3185 ..Roles::default()
3186 },
3187 graph: Graph {
3188 implementers: 1,
3189 ..Graph::default()
3190 },
3191 ..Config::default()
3192 };
3193 let roles = cfg.resolve_roles().unwrap();
3194 assert_eq!(roles.implementers.len(), 1);
3196 assert_eq!(roles.implementers[0].id, "c");
3197 let roster: Vec<&str> = roles
3198 .implementer_roster
3199 .iter()
3200 .map(|a| a.id.as_str())
3201 .collect();
3202 assert_eq!(roster, ["c", "a"]);
3203 }
3204
3205 #[test]
3206 fn explicit_roles_win() {
3207 let cfg = Config {
3208 agents: vec![spec("a"), spec("b")],
3209 roles: Roles {
3210 implementers: vec!["b".to_owned()],
3211 judges: vec!["a".to_owned()],
3212 reviewers: Vec::new(),
3213 fixer: Some("a".into()),
3214 ..Roles::default()
3215 },
3216 ..Config::default()
3217 };
3218 let roles = cfg.resolve_roles().unwrap();
3219 assert!(roles.implementers.iter().all(|a| a.id == "b"));
3220 assert!(roles.judges.iter().all(|a| a.id == "a"));
3221 let fixer = roles.fixer.unwrap();
3222 assert_eq!(fixer.len(), 1);
3223 assert_eq!(fixer[0].id, "a");
3224 assert_eq!(roles.conductor.id, "a");
3225 }
3226
3227 #[test]
3228 fn fixer_takes_a_string_or_an_ordered_chain() {
3229 let one: Roles = toml::from_str("fixer = \"a\"").unwrap();
3230 assert_eq!(one.fixer.as_ref().unwrap().ids(), ["a"]);
3231 let chain: Roles = toml::from_str("fixer = [\"b\", \"a\"]").unwrap();
3232 assert_eq!(chain.fixer.as_ref().unwrap().ids(), ["b", "a"]);
3233
3234 let resolve = |fixer: Option<AgentChoice>| {
3235 Config {
3236 agents: vec![spec("a"), spec("b"), spec("c")],
3237 roles: Roles {
3238 fixer,
3239 ..Roles::default()
3240 },
3241 ..Config::default()
3242 }
3243 .resolve_roles()
3244 };
3245 let ids = |r: &ResolvedRoles| -> Vec<String> {
3246 r.fixer
3247 .as_ref()
3248 .unwrap()
3249 .iter()
3250 .map(|s| s.id.clone())
3251 .collect()
3252 };
3253 assert_eq!(ids(&resolve(Some("c".into())).unwrap()), ["c"]);
3255 assert!(resolve(None).unwrap().fixer.is_none());
3256 let chain = AgentChoice::Chain(vec!["b".into(), "zzz".into(), "a".into(), "b".into()]);
3258 assert_eq!(ids(&resolve(Some(chain)).unwrap()), ["b", "a"]);
3259 let err = resolve(Some(AgentChoice::Chain(vec!["zzz".into()]))).unwrap_err();
3261 assert!(format!("{err:#}").contains("fixer"), "{err:#}");
3262 }
3263
3264 #[test]
3265 fn unknown_agent_id_is_an_error() {
3266 let cfg = Config {
3267 agents: vec![spec("a")],
3268 roles: Roles {
3269 judges: vec!["nope".to_owned()],
3270 ..Roles::default()
3271 },
3272 ..Config::default()
3273 };
3274 assert!(cfg.resolve_roles().is_err());
3275 }
3276
3277 #[test]
3278 fn conductor_role_is_resolved_validated_and_has_a_fallback() {
3279 let mut cfg = Config {
3280 agents: vec![spec("a"), spec("b")],
3281 ..Config::default()
3282 };
3283 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "a");
3284
3285 cfg.roles.conductor = Some("b".into());
3286 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "b");
3287
3288 cfg.roles.conductor = Some("missing".into());
3289 assert!(cfg.resolve_roles().is_err());
3290 }
3291
3292 #[test]
3293 fn a_standalone_role_takes_a_string_or_an_array_and_round_trips() {
3294 let one: Roles = toml::from_str("synthesizer = \"opus\"").unwrap();
3295 assert_eq!(one.synthesizer, Some(AgentChoice::One("opus".to_owned())));
3296 assert_eq!(primary(one.synthesizer.as_ref()), Some("opus"));
3297
3298 let chain: Roles = toml::from_str("chatter = [\"opus\", \"codex\"]").unwrap();
3299 assert_eq!(chain.chatter.as_ref().unwrap().ids(), ["opus", "codex"]);
3300 assert_eq!(primary(chain.chatter.as_ref()), Some("opus"));
3301
3302 for roles in [one, chain] {
3303 let text = toml::to_string(&roles).unwrap();
3304 let back: Roles = toml::from_str(&text).unwrap();
3305 assert_eq!(back.synthesizer, roles.synthesizer);
3306 assert_eq!(back.chatter, roles.chatter);
3307 }
3308 let text = toml::to_string(&Roles {
3309 conductor: Some("x".into()),
3310 ..Roles::default()
3311 })
3312 .unwrap();
3313 assert!(
3314 text.contains("conductor = \"x\""),
3315 "string stays a string: {text}"
3316 );
3317 assert!(toml::from_str::<Roles>("synthesizer = 3").is_err());
3318 }
3319
3320 #[test]
3321 fn dupes_judge_role_accepts_strings_and_chains_and_round_trips() {
3322 for (text, ids) in [
3323 (r#"dupes_judge = "dedicated""#, vec!["dedicated"]),
3324 (
3325 r#"dupes_judge = ["first", "second"]"#,
3326 vec!["first", "second"],
3327 ),
3328 ("dupes_judge = []", vec![]),
3329 ] {
3330 let roles: Roles = toml::from_str(text).unwrap();
3331 assert_eq!(roles.dupes_judge.as_ref().unwrap().ids(), ids);
3332 let serialized = toml::to_string(&roles).unwrap();
3333 let back: Roles = toml::from_str(&serialized).unwrap();
3334 assert_eq!(back.dupes_judge, roles.dupes_judge);
3335 assert!(serialized.contains(text));
3336 }
3337 assert!(toml::from_str::<Roles>("dupes_judge = 3").is_err());
3338 assert!(Roles::default().dupes_judge.is_none());
3339 assert!(Config::starter_toml().contains("# dupes_judge ="));
3340
3341 let mut cfg = Config {
3343 agents: vec![spec("a")],
3344 ..Config::default()
3345 };
3346 cfg.roles.dupes_judge = Some("missing".into());
3347 assert!(cfg.resolve_roles().is_ok());
3348 }
3349
3350 #[test]
3351 fn an_empty_choice_counts_as_unset() {
3352 assert!(AgentChoice::Chain(Vec::new()).ids().is_empty());
3353 assert!(AgentChoice::One(" ".to_owned()).ids().is_empty());
3354 assert_eq!(primary(Some(&AgentChoice::Chain(vec![]))), None);
3355 }
3356
3357 #[test]
3358 fn synthesizer_role_is_a_lazy_lookup_with_the_same_fallback_as_chatter() {
3359 let mut cfg = Config {
3365 agents: vec![spec("a"), spec("b")],
3366 ..Config::default()
3367 };
3368 let want = primary(cfg.roles.synthesizer.as_ref());
3369 assert_eq!(
3370 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
3371 .unwrap()
3372 .id,
3373 "a",
3374 "unset falls back to agent::pick's own default order"
3375 );
3376
3377 cfg.roles.synthesizer = Some("b".into());
3378 let want = primary(cfg.roles.synthesizer.as_ref());
3379 assert_eq!(
3380 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
3381 .unwrap()
3382 .id,
3383 "b",
3384 "the named agent wins over the default order"
3385 );
3386 }
3387
3388 #[test]
3389 fn empty_roster_is_an_error() {
3390 assert!(Config::default().resolve_roles().is_err());
3391 }
3392
3393 #[test]
3394 fn advise_defaults_to_on_with_three_proposals() {
3395 let g = Graph::default();
3396 assert!(g.advise);
3397 assert!(g.graft_runner_up, "graft is on by default");
3398 assert_eq!(g.advisors, 3);
3399 }
3400
3401 #[test]
3402 fn unset_advisors_falls_back_to_the_judge_roster() {
3403 let cfg = Config {
3404 agents: vec![spec("a"), spec("b")],
3405 roles: Roles {
3406 judges: vec!["b".to_owned()],
3407 ..Roles::default()
3408 },
3409 graph: Graph {
3410 advisors: 2,
3411 ..Graph::default()
3412 },
3413 ..Config::default()
3414 };
3415 let advisors = cfg.advisors().expect("advisors resolve");
3416 assert_eq!(advisors.len(), 2);
3417 assert!(
3418 advisors.iter().all(|a| a.id == "b"),
3419 "an unset [roles] advisors must fall back to [roles] judges: {advisors:?}"
3420 );
3421 }
3422
3423 #[test]
3424 fn an_explicit_advisor_roster_wins_over_the_judge_fallback() {
3425 let cfg = Config {
3426 agents: vec![spec("a"), spec("b")],
3427 roles: Roles {
3428 judges: vec!["b".to_owned()],
3429 advisors: vec!["a".to_owned()],
3430 ..Roles::default()
3431 },
3432 graph: Graph {
3433 advisors: 2,
3434 ..Graph::default()
3435 },
3436 ..Config::default()
3437 };
3438 let advisors = cfg.advisors().expect("advisors resolve");
3439 assert!(advisors.iter().all(|a| a.id == "a"));
3440 }
3441
3442 #[test]
3448 fn an_unconfigured_advisor_and_judge_roster_resolve_to_the_same_agents() {
3449 let cfg = Config {
3450 agents: vec![spec("a"), spec("b"), spec("c")],
3451 graph: Graph {
3452 advisors: 3,
3453 judges: 3,
3454 ..Graph::default()
3455 },
3456 ..Config::default()
3457 };
3458 let advisors = cfg.advisors().expect("advisors resolve");
3459 let judges = cfg.resolve_roles().expect("roles resolve").judges;
3460 let advisor_ids: Vec<&str> = advisors.iter().map(|a| a.id.as_str()).collect();
3461 let judge_ids: Vec<&str> = judges.iter().map(|a| a.id.as_str()).collect();
3462 assert_eq!(
3463 advisor_ids, judge_ids,
3464 "an unconfigured advisor roster must be the same seats an unconfigured judge panel gets"
3465 );
3466 }
3467
3468 #[test]
3469 fn an_unresolvable_advisor_seat_is_an_error_naming_the_id() {
3470 let cfg = Config {
3471 agents: vec![spec("a")],
3472 roles: Roles {
3473 advisors: vec!["nope".to_owned()],
3474 ..Roles::default()
3475 },
3476 graph: Graph {
3477 advisors: 1,
3478 ..Graph::default()
3479 },
3480 ..Config::default()
3481 };
3482 let err = cfg.advisors().expect_err("`nope` is not in the roster");
3483 assert!(format!("{err:#}").contains("nope"));
3484 }
3485
3486 #[test]
3487 fn repos_default_to_no_roots_and_a_day_of_trust() {
3488 assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
3489 assert_eq!(Config::default().repos.scan_ttl, 86_400);
3490 assert_eq!(Config::default().repos.fetch_interval, 600);
3491 }
3492
3493 #[test]
3494 fn a_config_file_with_no_repos_table_still_loads() {
3495 let dir = tempfile::tempdir().unwrap();
3496 let path = dir.path().join("magi.toml");
3497 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
3498 let cfg = Config::load(&path).expect("must load without [repos]");
3499 assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
3500 assert_eq!(cfg.repos.scan_ttl, 86_400);
3501 }
3502
3503 #[test]
3518 fn a_test_build_does_not_read_the_operators_machine_config() {
3519 let repo = tempfile::tempdir().unwrap();
3520 std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
3521
3522 let layers = Config::layers(repo.path());
3523 assert_eq!(
3524 layers,
3525 vec![repo.path().join("magi.toml")],
3526 "only the fixture's own file may be a layer"
3527 );
3528 if let Some(real) = dirs::config_dir() {
3529 let machine = real.join("magi").join("config.toml");
3530 assert!(
3531 !layers.contains(&machine),
3532 "the operator's {} must not be a layer in a test build",
3533 machine.display()
3534 );
3535 }
3536 }
3537
3538 #[test]
3539 fn starter_toml_loads_through_teravars() {
3540 let dir = tempfile::tempdir().unwrap();
3541 let path = dir.path().join("magi.toml");
3542 std::fs::write(&path, Config::starter_toml()).unwrap();
3543 let parsed = Config::load(&path).expect("starter config must load");
3544 assert_eq!(parsed.graph.implementers, 3);
3545 assert_eq!(parsed.merge.mode, MergeMode::None);
3546 assert_eq!(parsed.merge.style, MergeStyle::Merge);
3547 assert!(parsed.graph.sessions);
3548 assert!(parsed.graph.github_text_guard);
3549 assert_eq!(parsed.graph.timeout_review, 1200);
3550 assert_eq!(parsed.graph.verify_timeout(), 1200);
3551 assert_eq!(parsed.update.mode, UpdateMode::Notify);
3552 }
3553
3554 #[test]
3555 fn release_defaults_to_actions_and_the_starter_documents_it() {
3556 let dir = tempfile::tempdir().unwrap();
3557 let path = dir.path().join("magi.toml");
3558 std::fs::write(&path, Config::starter_toml()).unwrap();
3559 let r = Config::load(&path).unwrap().release;
3560 assert_eq!(r.mode, ReleaseMode::Actions);
3561 assert!(!r.is_local());
3562 assert!(r.commands.is_empty());
3563 assert_eq!(r.timeout_minutes, 30);
3564 assert!(Config::starter_toml().contains("# mode = \"actions\""));
3565 }
3566
3567 #[test]
3568 fn release_local_parses_and_unknown_keys_are_refused() {
3569 let dir = tempfile::tempdir().unwrap();
3570 let path = dir.path().join("magi.toml");
3571 std::fs::write(
3572 &path,
3573 "[release]\nmode = \"local\"\ncommands = [\"true\", \"echo $MAGI_RELEASE_TAG\"]\ntimeout_minutes = 5\n",
3574 )
3575 .unwrap();
3576 let r = Config::load(&path).unwrap().release;
3577 assert!(r.is_local());
3578 assert_eq!(r.commands.len(), 2);
3579 assert_eq!(r.timeout_minutes, 5);
3580 std::fs::write(&path, "[release]\nmode = \"local\"\nbogus = 1\n").unwrap();
3581 assert!(Config::load(&path).is_err());
3582 std::fs::write(&path, "[release]\nmode = \"gha\"\n").unwrap();
3583 assert!(Config::load(&path).is_err());
3584 }
3585
3586 #[test]
3587 fn pre_gate_defaults_to_empty_and_the_starter_documents_it() {
3588 let dir = tempfile::tempdir().unwrap();
3589 let path = dir.path().join("magi.toml");
3590 std::fs::write(&path, Config::starter_toml()).unwrap();
3591 assert!(Config::load(&path).unwrap().verify.pre_gate.is_empty());
3592 assert!(Config::starter_toml().contains("# pre_gate = []"));
3593 }
3594
3595 #[test]
3596 fn starter_toml_explains_inherited_and_explicit_verify_timeouts() {
3597 let starter = Config::starter_toml();
3598 assert!(starter.contains("When timeout_verify is omitted, E2E and"));
3599 assert!(starter.contains("verification independent if timeout_review changes later"));
3600 assert!(starter.contains("# timeout_verify = 1200"));
3601 }
3602
3603 #[test]
3604 fn starter_toml_documents_chat_personas() {
3605 let starter = Config::starter_toml();
3606 assert!(starter.contains("# [[talk.personas]]"));
3607 assert!(starter.contains("tone only"));
3608 }
3609
3610 #[test]
3611 fn talk_personas_parse_and_are_validated() {
3612 let dir = tempfile::tempdir().unwrap();
3613 let path = dir.path().join("magi.toml");
3614 std::fs::write(
3615 &path,
3616 "[[talk.personas]]\nid = \"rei\"\nname = \"Quiet\"\nprompt = \"Be brief.\"\n\n\
3617 [[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n",
3618 )
3619 .unwrap();
3620 let cfg = Config::load(&path).expect("loads");
3621 assert_eq!(cfg.talk.personas.len(), 2);
3622 let catalog = crate::persona::catalog(&cfg.talk.personas);
3623 let rei = catalog.iter().find(|p| p.id == "rei").unwrap();
3624 assert_eq!(
3625 (rei.name.as_str(), rei.prompt.as_str()),
3626 ("Quiet", "Be brief.")
3627 );
3628 assert_eq!(catalog.last().unwrap().id, "gendo");
3629
3630 for (body, needle) in [
3631 (
3632 "[[talk.personas]]\nid = \"\"\nname = \"n\"\nprompt = \"p\"\n",
3633 "empty `id`",
3634 ),
3635 (
3636 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \" \"\n",
3637 "empty `prompt`",
3638 ),
3639 (
3640 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n\
3641 [[talk.personas]]\nid = \"a\"\nname = \"m\"\nprompt = \"q\"\n",
3642 "more than once",
3643 ),
3644 (
3645 "[[talk.personas]]\nid = \"default\"\nname = \"n\"\nprompt = \"p\"\n",
3646 "cannot be redefined",
3647 ),
3648 ] {
3649 std::fs::write(&path, body).unwrap();
3650 let err = format!("{:#}", Config::load(&path).unwrap_err());
3651 assert!(err.contains(needle), "{needle}: {err}");
3652 }
3653 }
3654
3655 #[test]
3656 fn talk_operator_name_is_trimmed_and_validated() {
3657 let dir = tempfile::tempdir().unwrap();
3658 let path = dir.path().join("magi.toml");
3659 let load = |body: &str| {
3660 std::fs::write(&path, body).unwrap();
3661 Config::load(&path)
3662 };
3663 let ok = load("[talk]\noperator_name = \" Commander \"\n").expect("ok");
3664 assert_eq!(ok.talk.operator_name(), Some("Commander"));
3665 let blank = load("[talk]\noperator_name = \" \"\n").expect("blank");
3666 assert_eq!(blank.talk.operator_name(), None);
3667 assert!(load("[talk]\noperator_name = \"a\\nb\"\n").is_err());
3668 let long = "x".repeat(65);
3669 assert!(load(&format!("[talk]\noperator_name = \"{long}\"\n")).is_err());
3670 }
3671
3672 #[test]
3673 fn talk_persona_icon_parses_and_a_bad_shape_keeps_config_usable() {
3674 let dir = tempfile::tempdir().unwrap();
3675 let load = |body: &str| {
3676 let path = dir.path().join("c.toml");
3677 std::fs::write(&path, body).unwrap();
3678 Config::load(&path)
3679 };
3680 let ok = load(
3681 "[[talk.personas]]\nid = \"rei\"\nicon = \"~/rei.png\"\n\n\
3682 [[talk.personas]]\nid = \"default\"\nicon = \"data:image/png;base64,AAAA\"\n",
3683 )
3684 .unwrap();
3685 let c = crate::persona::catalog(&ok.talk.personas);
3686 assert_eq!(c[0].icon.as_deref(), Some("data:image/png;base64,AAAA"));
3687 assert_eq!(c[2].icon.as_deref(), Some("~/rei.png"));
3688 assert!(c[2].prompt.contains("Rei"), "built-in voice kept");
3689 let oversized = format!(
3690 "data:image/png;base64,{}",
3691 "A".repeat(crate::persona_icon::ICON_MAX_BYTES)
3692 );
3693 for bad in ["", "rei.png", "/a/b.svg", "/a/../b.png", &oversized] {
3694 for (id, fields) in [
3695 ("rei", ""),
3696 ("default", ""),
3697 ("custom", "name = \"Custom\"\nprompt = \"Keep calm\"\n"),
3698 ] {
3699 let body = format!("[[talk.personas]]\nid = \"{id}\"\nicon = \"{bad}\"\n{fields}");
3700 let cfg = load(&body).expect("bad icon must not invalidate config");
3701 let persona = crate::persona::find(&cfg.talk.personas, id).unwrap();
3702 assert_eq!(persona.id, id);
3703 assert!(crate::persona_icon::load(bad).is_err());
3704 }
3705 }
3706 let doc = Config::starter_toml();
3707 assert!(doc.contains("# icon = "));
3708 }
3709
3710 #[test]
3711 fn talk_personas_in_two_layers_are_refused() {
3712 let dir = tempfile::tempdir().unwrap();
3713 let machine = dir.path().join("machine.toml");
3714 let repo = dir.path().join("repo.toml");
3715 let one = "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n";
3716 std::fs::write(&machine, one).unwrap();
3717 std::fs::write(&repo, one.replace("\"a\"", "\"b\"")).unwrap();
3718 let err = format!("{:#}", Config::load_layers(&[machine, repo]).unwrap_err());
3719 assert!(err.contains("talk.personas"), "{err}");
3720 }
3721
3722 #[test]
3723 fn starter_toml_documents_role_lists_as_backup_order() {
3724 let starter = Config::starter_toml();
3725 assert!(starter.contains("also an ordered backup list"));
3726 assert!(starter.contains("codex then sonnet are spares"));
3727 }
3728
3729 #[test]
3733 fn a_repository_can_declare_a_linear_history_merge_style() {
3734 let dir = tempfile::tempdir().unwrap();
3735 let path = dir.path().join("magi.toml");
3736 std::fs::write(&path, "[merge]\nmode = \"none\"\nstyle = \"squash\"\n").unwrap();
3737 let parsed = Config::load(&path).expect("config must load");
3738 assert_eq!(parsed.merge.style, MergeStyle::Squash);
3739 }
3740
3741 #[test]
3742 fn later_layers_win_and_vars_render() {
3743 let dir = tempfile::tempdir().unwrap();
3744 let machine = dir.path().join("machine.toml");
3745 let project = dir.path().join("magi.toml");
3746 std::fs::write(
3748 &machine,
3749 "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
3750 [graph]\ncandidates = 3\nmax_parallel = 8\n",
3751 )
3752 .unwrap();
3753 std::fs::write(
3756 &project,
3757 "[vars]\ncache = \"/shared\"\n\n\
3758 [graph]\ncandidates = 2\n\n\
3759 [verify]\ngate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
3760 )
3761 .unwrap();
3762
3763 let cfg = Config::load_layers(&[machine, project]).expect("layered load");
3764 assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
3765 assert_eq!(cfg.graph.implementers, 2, "project layer wins");
3766 assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
3767 assert_eq!(
3768 cfg.verify.gate,
3769 ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
3770 );
3771 assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
3773 }
3774
3775 #[test]
3776 fn talk_defaults_to_an_hour_and_an_unwritten_config_still_gets_it() {
3777 let g = Graph::default();
3781 assert_eq!(g.timeout_talk, 3600);
3782
3783 let dir = tempfile::tempdir().unwrap();
3784 let path = dir.path().join("magi.toml");
3785 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
3786 let cfg = Config::load(&path).expect("must load without timeout_talk set");
3787 assert_eq!(cfg.graph.timeout_talk, 3600);
3788 }
3789
3790 #[test]
3791 fn an_overridden_talk_timeout_reaches_the_loaded_config() {
3792 let dir = tempfile::tempdir().unwrap();
3793 let path = dir.path().join("magi.toml");
3794 std::fs::write(&path, "[graph]\ntimeout_talk = 120\n").unwrap();
3795 let cfg = Config::load(&path).expect("must load");
3796 assert_eq!(cfg.graph.timeout_talk, 120);
3797 }
3798
3799 #[test]
3800 fn the_disk_defaults_are_the_measurements_made_up_front() {
3801 let cfg = Config::default();
3802 assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
3803 assert!(cfg.disk.auto_fold);
3804 assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
3805 assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
3806 }
3807
3808 #[test]
3809 fn an_unset_disk_section_is_the_safe_default() {
3810 let dir = tempfile::tempdir().unwrap();
3811 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
3812 let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
3813 assert_eq!(cfg.disk, Disk::default());
3814 }
3815
3816 #[test]
3817 fn env_is_available_to_templates_with_a_default() {
3818 let dir = tempfile::tempdir().unwrap();
3819 let path = dir.path().join("magi.toml");
3820 std::fs::write(
3828 &path,
3829 "[verify]\n\
3830 gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
3831 \"populated={{ env | length > 0 }}\"]\n",
3832 )
3833 .unwrap();
3834 let cfg = Config::load(&path).expect("env lookup must render");
3835 assert_eq!(cfg.verify.gate[0], "cache=fallback");
3836 assert_eq!(cfg.verify.gate[1], "populated=true");
3837 }
3838
3839 #[test]
3840 fn a_broken_template_names_the_file() {
3841 let dir = tempfile::tempdir().unwrap();
3842 let path = dir.path().join("magi.toml");
3843 std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
3844 let err = Config::load(&path).expect_err("must not silently ignore");
3845 assert!(err.to_string().contains("teravars"), "{err}");
3846 }
3847
3848 #[test]
3849 fn tera_syntax_in_comments_is_inert() {
3850 let dir = tempfile::tempdir().unwrap();
3854 let path = dir.path().join("magi.toml");
3855 std::fs::write(
3856 &path,
3857 "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
3858 [graph]\ncandidates = 2\n",
3859 )
3860 .unwrap();
3861 let cfg = Config::load(&path).expect("comments must be inert, not rendered");
3862 assert_eq!(cfg.graph.implementers, 2);
3863 }
3864
3865 #[test]
3866 fn opencode_defaults_to_file_delivery() {
3867 let mut s = spec("oc");
3868 s.kind = AgentKind::Opencode;
3869 assert_eq!(s.delivery(), Delivery::File);
3870 s.prompt_delivery = Some(Delivery::Argv);
3871 assert_eq!(s.delivery(), Delivery::Argv);
3872 }
3873 #[test]
3874 fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
3875 let g = Graph::default();
3880 assert!(
3881 g.land,
3882 "stopping at an open PR left the watching to a human"
3883 );
3884 assert!(
3885 g.land_approval,
3886 "on-by-default land is only defensible while this is also on"
3887 );
3888 assert!(g.land_rounds > 0, "a loop with no budget never terminates");
3889 assert!(
3890 g.hold_contested_merge,
3891 "a contested hand-off must still reach a human when approvals are off"
3892 );
3893 }
3894 #[test]
3895 fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
3896 let dir = tempfile::tempdir().unwrap();
3900 let machine = dir.path().join("machine.toml");
3901 let repo = dir.path().join("magi.toml");
3902 std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
3903 std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
3904
3905 let err = Config::load_layers(&[machine.clone(), repo.clone()])
3906 .expect_err("two layers naming one array must not merge silently");
3907 assert_eq!(
3908 err.downcast_ref::<ConfigFailure>().unwrap().stage,
3909 "config-merge"
3910 );
3911 let err = err.to_string();
3912 assert!(err.contains("roles.implementers"), "{err}");
3913 assert!(err.contains("machine.toml"), "{err}");
3916 assert!(err.contains("magi.toml"), "{err}");
3917 }
3918
3919 #[test]
3920 fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
3921 let dir = tempfile::tempdir().unwrap();
3924 let machine = dir.path().join("machine.toml");
3925 let repo = dir.path().join("magi.toml");
3926 std::fs::write(&machine, "[roles]\nchatter = \"opus\"\n").unwrap();
3927 std::fs::write(
3928 &repo,
3929 "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
3930 [roles]\nimplementers = [\"oc\"]\n",
3931 )
3932 .unwrap();
3933
3934 let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
3935 assert_eq!(primary(cfg.roles.chatter.as_ref()), Some("opus"));
3936 assert_eq!(cfg.roles.implementers, ["oc"]);
3937 assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
3938 }
3939
3940 #[test]
3941 fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
3942 let dir = tempfile::tempdir().unwrap();
3945 let machine = dir.path().join("machine.toml");
3946 let repo = dir.path().join("magi.toml");
3947 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
3948 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
3949
3950 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
3951 assert_eq!(
3952 cfg.verify.gate,
3953 [
3954 "editorconfig-checker".to_owned(),
3955 "cargo make check".to_owned()
3956 ],
3957 "low-priority (machine) command first, high-priority (repo) command after"
3958 );
3959 }
3960
3961 fn load_one(body: &str) -> Result<Config> {
3962 let dir = tempfile::tempdir().unwrap();
3963 let path = dir.path().join("magi.toml");
3964 std::fs::write(&path, body).unwrap();
3965 Config::load_layers(&[path])
3966 }
3967
3968 #[test]
3969 fn worktree_setup_defaults_to_empty_and_parses_steps() {
3970 assert!(Config::default().worktree.setup.is_empty());
3971 let cfg = load_one(
3972 "[worktree]\nsetup = [\n { copy = \".env.example -> .env\" },\n \
3973 { copy = \"x\", optional = true },\n { run = \"true\", timeout_secs = 5 },\n]\n",
3974 )
3975 .unwrap();
3976 assert_eq!(cfg.worktree.setup.len(), 3);
3977 assert!(cfg.worktree.setup[1].optional);
3978 assert_eq!(cfg.worktree.setup[2].timeout_secs, Some(5));
3979 }
3980
3981 #[test]
3982 fn worktree_setup_rejects_malformed_steps() {
3983 for bad in [
3984 "{ copy = \"a\", run = \"b\" }",
3985 "{ optional = true }",
3986 "{ copy = \"a -> ../b\" }",
3987 "{ copy = \"a -> /abs\" }",
3988 "{ copy = \"a -> .git/config\" }",
3989 "{ run = \"b\", optional = true }",
3990 "{ copy = \"a\", timeout_secs = 3 }",
3991 "{ run = \"b\", bogus = 1 }",
3992 ] {
3993 let body = format!("[worktree]\nsetup = [{bad}]\n");
3994 assert!(load_one(&body).is_err(), "{bad}");
3995 }
3996 }
3997
3998 #[test]
3999 fn worktree_setup_in_two_layers_is_refused() {
4000 let dir = tempfile::tempdir().unwrap();
4001 let machine = dir.path().join("machine.toml");
4002 let repo = dir.path().join("magi.toml");
4003 std::fs::write(&machine, "[worktree]\nsetup = [{ run = \"a\" }]\n").unwrap();
4004 std::fs::write(&repo, "[worktree]\nsetup = [{ run = \"b\" }]\n").unwrap();
4005 assert!(Config::load_layers(&[machine, repo]).is_err());
4006 }
4007
4008 #[test]
4009 fn starter_toml_documents_worktree_setup() {
4010 let starter = Config::starter_toml();
4011 assert!(starter.contains("# [worktree]") && starter.contains("setup = ["));
4012 let body = starter.replace("# [worktree]", "[worktree]");
4014 let mut out = String::new();
4015 let mut live = false;
4016 for line in body.lines() {
4017 if line == "[worktree]" {
4018 live = true;
4019 } else if live && !line.starts_with("# ") {
4020 live = false;
4021 }
4022 out.push_str(&if live {
4023 line.replacen("# ", "", 1)
4024 } else {
4025 line.to_owned()
4026 });
4027 out.push('\n');
4028 }
4029 let cfg = load_one(&out).expect("uncommented example loads");
4030 assert_eq!(cfg.worktree.setup.len(), 3);
4031 }
4032
4033 #[test]
4034 fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
4035 let dir = tempfile::tempdir().unwrap();
4036 let machine = dir.path().join("machine.toml");
4037 let repo = dir.path().join("magi.toml");
4038 std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
4039 std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
4040
4041 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4042 assert_eq!(
4043 cfg.verify.e2e,
4044 ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
4045 );
4046 }
4047
4048 #[test]
4049 fn two_layers_declaring_repos_roots_are_both_scanned() {
4050 let dir = tempfile::tempdir().unwrap();
4051 let machine = dir.path().join("machine.toml");
4052 let repo = dir.path().join("magi.toml");
4053 std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
4054 std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
4055
4056 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4057 assert_eq!(
4058 cfg.repos.roots,
4059 [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
4060 );
4061 }
4062
4063 #[test]
4064 fn duplicate_gate_commands_across_layers_both_run() {
4065 let dir = tempfile::tempdir().unwrap();
4068 let machine = dir.path().join("machine.toml");
4069 let repo = dir.path().join("magi.toml");
4070 std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
4071 std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
4072
4073 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4074 assert_eq!(
4075 cfg.verify.gate,
4076 ["same-command".to_owned(), "same-command".to_owned()]
4077 );
4078 }
4079
4080 #[test]
4081 fn notify_command_is_still_refused_across_two_layers() {
4082 let dir = tempfile::tempdir().unwrap();
4084 let machine = dir.path().join("machine.toml");
4085 let repo = dir.path().join("magi.toml");
4086 std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
4087 std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
4088
4089 let err = Config::load_layers(&[machine.clone(), repo.clone()])
4090 .expect_err("an argv split across layers must not concatenate");
4091 assert_eq!(
4092 err.downcast_ref::<ConfigFailure>().unwrap().stage,
4093 "config-merge"
4094 );
4095 let err = err.to_string();
4096 assert!(err.contains("notify.command"), "{err}");
4097 assert!(err.contains("machine.toml"), "{err}");
4098 assert!(err.contains("magi.toml"), "{err}");
4099 }
4100
4101 #[test]
4102 fn one_layer_declaring_verify_gate_runs_unchanged() {
4103 let dir = tempfile::tempdir().unwrap();
4106 let path = dir.path().join("magi.toml");
4107 std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4108
4109 let cfg = Config::load(&path).expect("single layer must still load");
4110 assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
4111 }
4112
4113 #[test]
4114 fn layered_parse_failures_name_the_failing_input() {
4115 let dir = tempfile::tempdir().unwrap();
4116 let a = dir.path().join("a.toml");
4117 let b = dir.path().join("b.toml");
4118 std::fs::write(&a, "[graph").unwrap();
4119 std::fs::write(&b, "[verify").unwrap();
4120 let paths = [a.clone(), b.clone()];
4121 let first = Config::load_layers(&paths).unwrap_err();
4122 let first_cause = first.downcast_ref::<ConfigFailure>().unwrap();
4123 assert_eq!(first_cause.stage, "config-parse");
4124 assert_eq!(first_cause.target, serde_json::to_string(&[&a]).unwrap());
4125 std::fs::write(&a, "").unwrap();
4126 let second = Config::load_layers(&paths).unwrap_err();
4127 let second_cause = second.downcast_ref::<ConfigFailure>().unwrap();
4128 assert_eq!(second_cause.stage, "config-parse");
4129 assert_eq!(second_cause.target, serde_json::to_string(&[&b]).unwrap());
4130 assert_ne!(first_cause.target, second_cause.target);
4131 }
4132
4133 #[test]
4134 fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
4135 let dir = tempfile::tempdir().unwrap();
4136 let machine = dir.path().join("machine.toml");
4137 let repo = dir.path().join("magi.toml");
4138 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
4139 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4140 let paths = vec![machine.clone(), repo.clone()];
4141
4142 let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
4143 let described =
4144 Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
4145 assert!(described.contains("editorconfig-checker && cargo make check"));
4146 assert!(
4147 described.contains(&machine.display().to_string()),
4148 "{described}"
4149 );
4150 assert!(
4151 described.contains(&repo.display().to_string()),
4152 "{described}"
4153 );
4154
4155 let single = vec![repo.clone()];
4157 let solo_cfg = Config::load_layers(&single).expect("single layer loads");
4158 let solo_described =
4159 Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
4160 assert_eq!(solo_described, "cargo make check");
4161 }
4162
4163 mod remote_layers {
4164 use super::*;
4165
4166 fn git(dir: &Path, args: &[&str]) {
4167 use crate::proc::Quiet as _;
4168 let out = std::process::Command::new("git")
4169 .args(args)
4170 .quiet()
4171 .current_dir(dir)
4172 .output()
4173 .unwrap();
4174 assert!(out.status.success(), "git {args:?}: {out:?}");
4175 }
4176
4177 fn fixture(remote: &str, disk: &str) -> (tempfile::TempDir, PathBuf) {
4180 let tmp = tempfile::tempdir().unwrap();
4181 let bare = tmp.path().join("o.git");
4182 git(tmp.path(), &["init", "--bare", "-b", "trunk", "o.git"]);
4183 let repo = tmp.path().join("repo");
4184 std::fs::create_dir_all(&repo).unwrap();
4185 git(&repo, &["init", "-b", "trunk"]);
4186 git(&repo, &["config", "user.name", "t"]);
4187 git(&repo, &["config", "user.email", "t@example.com"]);
4188 std::fs::write(repo.join("magi.toml"), remote).unwrap();
4189 git(&repo, &["add", "-A"]);
4190 git(&repo, &["commit", "-m", "x"]);
4191 git(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
4192 git(&repo, &["push", "origin", "trunk"]);
4193 git(&repo, &["fetch", "origin"]);
4194 git(&repo, &["remote", "set-head", "origin", "trunk"]);
4195 std::fs::write(repo.join("magi.toml"), disk).unwrap();
4196 (tmp, repo)
4197 }
4198
4199 #[tokio::test]
4200 async fn branch_owner_holds_only_add_literal_true_values() {
4201 for (text, expected) in [
4202 ("[graph]\nland_approval = true\n", true),
4203 ("[graph]\nland_approval = false\n", false),
4204 ("[graph]\nland = true\n", false),
4205 ("[graph\n", false),
4206 ("[graph]\nland_approval = \"yes\"\n", false),
4207 ("[graph]\nland_approval = 1\n", false),
4208 ] {
4209 let (_tmp, repo) = fixture(text, "[graph]\nland_approval = false\n");
4210 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
4211 let (holds, _) = branch_owner_holds(&repo, &head).await;
4212 assert_eq!(
4213 holds.contains(&(OwnerHold::LandApproval, "magi.toml".into())),
4214 expected
4215 );
4216 assert!(
4217 !holds
4218 .iter()
4219 .any(|(h, _)| *h == OwnerHold::HoldContestedMerge)
4220 );
4221 for base in [false, true] {
4222 let mut cfg = Config::default();
4223 cfg.graph.land_approval = base;
4224 let mut state = crate::run::RunState::new(
4225 repo.clone(),
4226 "trunk".into(),
4227 head.clone(),
4228 "review".into(),
4229 cfg,
4230 );
4231 state.observe_branch_owner_holds(&head).await;
4232 assert!(
4233 state.branch_owner_holds.is_empty(),
4234 "competition candidates are excluded"
4235 );
4236 state.reviewed_commits = Some(Vec::new());
4237 state.observe_branch_owner_holds(&head).await;
4238 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base || expected);
4239 }
4240 }
4241 }
4242
4243 #[tokio::test]
4244 async fn branch_owner_holds_missing_and_unreadable_preserve_base() {
4245 let (_tmp, repo) = fixture(
4246 "[graph]\nland_approval = true\n",
4247 "[graph]\nland_approval = true\n",
4248 );
4249 git(&repo, &["rm", "magi.toml"]);
4250 std::fs::create_dir(repo.join(".magi")).unwrap();
4251 std::fs::write(
4252 repo.join(".magi/config.toml"),
4253 "[graph]\nhold_contested_merge = true\n",
4254 )
4255 .unwrap();
4256 git(&repo, &["add", "."]);
4257 git(&repo, &["commit", "-m", "nested hold"]);
4258 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
4259 let (holds, _) = branch_owner_holds(&repo, &head).await;
4260 assert_eq!(
4261 holds,
4262 [(OwnerHold::HoldContestedMerge, ".magi/config.toml".into())]
4263 );
4264 let (holds, diagnostics) =
4265 branch_owner_holds(&repo, "0000000000000000000000000000000000000000").await;
4266 assert!(holds.is_empty());
4267 assert!(!diagnostics.is_empty());
4268 let (holds, diagnostics) = branch_owner_holds(&repo, "").await;
4269 assert!(holds.is_empty());
4270 assert!(!diagnostics.is_empty());
4271 for base in [false, true] {
4272 let mut cfg = Config::default();
4273 cfg.graph.land_approval = base;
4274 let mut state = crate::run::RunState::new(
4275 repo.clone(),
4276 "trunk".into(),
4277 head.clone(),
4278 "review".into(),
4279 cfg,
4280 );
4281 state.reviewed_commits = Some(Vec::new());
4282 state.observe_branch_owner_holds(&head).await;
4283 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
4284 state
4285 .observe_branch_owner_holds("0000000000000000000000000000000000000000")
4286 .await;
4287 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
4288 }
4289 }
4290
4291 #[test]
4292 fn reads_the_remote_blob_not_the_working_tree() {
4293 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4294 let (cfg, _) = Config::discover(&repo, None).unwrap();
4295 assert_eq!(cfg.graph.implementers, 2);
4296 }
4297
4298 #[test]
4299 fn detached_head_still_reads_the_remote() {
4300 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4301 git(&repo, &["checkout", "--detach"]);
4302 let (cfg, _) = Config::discover(&repo, None).unwrap();
4303 assert_eq!(cfg.graph.implementers, 2);
4304 }
4305
4306 #[test]
4307 fn a_missing_ref_is_an_error_not_a_fallback() {
4308 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4309 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
4310 let err = format!("{:#}", Config::discover(&repo, None).unwrap_err());
4311 assert!(err.contains("origin"), "{err}");
4312 }
4313
4314 #[test]
4315 fn merge_base_in_the_checkout_locates_the_ref() {
4316 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
4317 assert!(Config::discover(&repo, None).is_err());
4318 }
4319
4320 #[test]
4321 fn the_magi_dir_layer_is_read_too() {
4322 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4323 std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
4324 std::fs::create_dir_all(repo.join(".magi")).unwrap();
4325 std::fs::write(repo.join(".magi/config.toml"), "[graph]\njudges = 3\n").unwrap();
4326 git(&repo, &["add", "-A"]);
4327 git(&repo, &["commit", "-m", "y"]);
4328 git(&repo, &["push", "origin", "trunk"]);
4329 git(&repo, &["fetch", "origin"]);
4330 let (cfg, layers) = Config::discover(&repo, None).unwrap();
4331 assert_eq!((cfg.graph.implementers, cfg.graph.judges), (2, 3));
4332 assert_eq!(layers.len(), 2);
4333 }
4334
4335 #[test]
4336 fn an_include_in_a_repository_layer_resolves_against_the_same_commit() {
4337 let (_t, repo) = fixture("include = [\"gate.toml\"]\n", "");
4338 std::fs::write(repo.join("magi.toml"), "include = [\"gate.toml\"]\n").unwrap();
4339 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 2\n").unwrap();
4340 git(&repo, &["add", "-A"]);
4341 git(&repo, &["commit", "-m", "inc"]);
4342 git(&repo, &["push", "origin", "trunk"]);
4343 git(&repo, &["fetch", "origin"]);
4344 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 9\n").unwrap();
4346 let (cfg, _) = Config::discover(&repo, None).unwrap();
4347 assert_eq!(cfg.graph.implementers, 2);
4348 }
4349
4350 #[test]
4351 fn a_machine_layer_base_is_rendered_before_locating_the_ref() {
4352 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
4353 let m = t.path().join("machine.toml");
4354 std::fs::write(
4355 &m,
4356 "[merge]\nbase = \"{{ env.MAGI_TEST_NO_SUCH | default(value='trunk') }}\"\n",
4357 )
4358 .unwrap();
4359 let (remote, base) = {
4360 let probe = probe_merge(&m, &repo).unwrap();
4361 (probe.remote, probe.base)
4362 };
4363 assert_eq!((remote, base), (None, Some("trunk".to_owned())));
4364 }
4365
4366 #[test]
4367 fn a_machine_layer_base_sees_the_checkouts_repo_name() {
4368 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4369 let m = t.path().join("machine.toml");
4370 std::fs::write(&m, "[merge]\nbase = \"{{ repo_name }}\"\n").unwrap();
4371 let probe = probe_merge(&m, &repo).unwrap();
4372 assert_eq!(probe.base.as_deref(), Some("repo"));
4373 }
4374
4375 #[test]
4376 fn every_include_form_is_recognised() {
4377 assert!(declares_include("include = [\"a.toml\"]\n"));
4378 assert!(declares_include("\"include\" = [\"a.toml\"]\n"));
4379 assert!(declares_include("teravars = { include = [\"a.toml\"] }\n"));
4380 assert!(declares_include("[teravars]\ninclude = [\"a.toml\"]\n"));
4381 assert!(!declares_include("[graph]\ncandidates = 2\n"));
4382 }
4383
4384 #[test]
4385 fn an_explicit_config_is_read_as_named() {
4386 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4387 let own = t.path().join("own.toml");
4388 std::fs::write(&own, "[graph]\ncandidates = 4\n").unwrap();
4389 let (cfg, _) = Config::discover(&repo, Some(&own)).unwrap();
4390 assert_eq!(cfg.graph.implementers, 4);
4391 }
4392
4393 #[test]
4394 fn discover_fetched_fails_when_the_fetch_does() {
4395 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4396 std::fs::remove_dir_all(t.path().join("o.git")).unwrap();
4397 let rt = tokio::runtime::Builder::new_current_thread()
4398 .enable_all()
4399 .build()
4400 .unwrap();
4401 let err = rt
4402 .block_on(Config::discover_fetched(&repo, None))
4403 .unwrap_err();
4404 assert!(format!("{err:#}").contains("fetch"), "{err:#}");
4405 }
4406
4407 #[test]
4408 fn fetch_and_remote_parse_failures_have_distinct_verified_causes() {
4409 let (tmp, repo) = fixture("[graph\ncandidates = 2\n", "");
4410 let remote = tmp.path().join("o.git");
4411 let offline = tmp.path().join("offline.git");
4412 std::fs::rename(&remote, &offline).unwrap();
4413 let rt = tokio::runtime::Builder::new_current_thread()
4414 .enable_all()
4415 .build()
4416 .unwrap();
4417 let fetch = rt
4418 .block_on(Config::discover_fetched(&repo, None))
4419 .unwrap_err();
4420 let fetch_cause = fetch.downcast_ref::<ConfigFailure>().unwrap();
4421 assert_eq!(fetch_cause.stage, "config-fetch");
4422 assert_eq!(fetch_cause.target, "origin/trunk");
4423
4424 std::fs::rename(&offline, &remote).unwrap();
4425 let parse = rt
4426 .block_on(Config::discover_fetched(&repo, None))
4427 .unwrap_err();
4428 let parse_cause = parse.downcast_ref::<ConfigFailure>().unwrap();
4429 assert_eq!(parse_cause.stage, "config-parse");
4430 assert!(parse_cause.target.contains("magi.toml"));
4431 assert!(
4432 !parse_cause.target.contains("/magi/config/"),
4433 "cache commit paths are incidental"
4434 );
4435 assert_ne!(fetch_cause.stage, parse_cause.stage);
4436 }
4437
4438 #[test]
4439 fn discover_fetched_survives_a_fetch_that_leaves_no_origin_head() {
4440 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4443 git(&repo, &["remote", "set-head", "origin", "-d"]);
4444 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
4445 git(
4446 &repo,
4447 &["config", "remote.origin.followRemoteHEAD", "never"],
4448 );
4449 let rt = tokio::runtime::Builder::new_current_thread()
4450 .enable_all()
4451 .build()
4452 .unwrap();
4453 let (cfg, _) = rt.block_on(Config::discover_fetched(&repo, None)).unwrap();
4454 assert_eq!(cfg.graph.implementers, 2);
4455 }
4456
4457 #[test]
4458 fn a_non_git_directory_reads_its_files() {
4459 let dir = tempfile::tempdir().unwrap();
4460 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 4\n").unwrap();
4461 let (cfg, _) = Config::discover(dir.path(), None).unwrap();
4462 assert_eq!(cfg.graph.implementers, 4);
4463 }
4464 }
4465
4466 #[test]
4467 fn github_language_defaults_to_english_and_accepts_japanese() {
4468 let default: Graph = toml::from_str("").unwrap();
4469 assert_eq!(default.github_language, "en");
4470 assert!(default.github_english() && default.language_gate());
4471 let ja: Graph = toml::from_str("github_language = \"ja\"").unwrap();
4472 assert!(!ja.github_english() && !ja.language_gate());
4473 let only_ops: Graph = toml::from_str("language = \"ja\"").unwrap();
4475 assert!(only_ops.language_gate());
4476 let off: Graph = toml::from_str("github_text_guard = false").unwrap();
4477 assert!(!off.language_gate() && off.github_english());
4478 assert!(Config::starter_toml().contains("github_language = \"en\""));
4479 }
4480}