1use std::collections::BTreeMap;
44use std::path::{Path, PathBuf};
45
46use anyhow::{Context as _, Result, bail};
47use serde::{Deserialize, Serialize};
48
49#[derive(Debug, thiserror::Error)]
52#[error("{stage}: {target}")]
53pub(crate) struct ConfigFailure {
54 pub(crate) stage: &'static str,
55 pub(crate) target: String,
56}
57
58impl ConfigFailure {
59 fn render(error: &teravars::Error, paths: &[PathBuf]) -> Self {
60 let stage = match error {
61 teravars::Error::Io(_) => "config-read",
62 teravars::Error::Toml(_) | teravars::Error::Extract(_) => "config-parse",
63 teravars::Error::Render(_) => "config-template",
64 teravars::Error::IncludeCycle { .. } | teravars::Error::IncludeConflict { .. } => {
65 "config-include"
66 }
67 _ => "config-render",
68 };
69 Self::layers(stage, paths)
70 }
71
72 fn layers(stage: &'static str, paths: &[PathBuf]) -> Self {
73 let targets: Vec<_> = paths
74 .iter()
75 .map(|path| {
76 path.ancestors()
79 .find(|p| p.join(REPO_MARKER).is_file())
80 .and_then(|root| path.strip_prefix(root).ok())
81 .unwrap_or(path)
82 .to_string_lossy()
83 .into_owned()
84 })
85 .collect();
86 Self {
87 stage,
88 target: serde_json::to_string(&targets).expect("config paths"),
89 }
90 }
91}
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
95#[serde(rename_all = "lowercase")]
96pub enum AgentKind {
97 Claude,
99 Opencode,
101 Antigravity,
105 Codex,
109 Omp,
115 Command,
117}
118
119impl AgentKind {
120 pub fn program(self) -> Option<&'static str> {
122 match self {
123 Self::Claude => Some("claude"),
124 Self::Opencode => Some("opencode"),
125 Self::Antigravity => Some("agy"),
126 Self::Codex => Some("codex"),
127 Self::Omp => Some("omp"),
128 Self::Command => None,
129 }
130 }
131
132 pub fn as_str(self) -> &'static str {
134 match self {
135 Self::Claude => "claude",
136 Self::Opencode => "opencode",
137 Self::Antigravity => "antigravity",
138 Self::Codex => "codex",
139 Self::Omp => "omp",
140 Self::Command => "command",
141 }
142 }
143
144 pub const ALL: [Self; 6] = [
152 Self::Claude,
153 Self::Opencode,
154 Self::Antigravity,
155 Self::Codex,
156 Self::Omp,
157 Self::Command,
158 ];
159}
160
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
163#[serde(rename_all = "lowercase")]
164pub enum Delivery {
165 Stdin,
167 Argv,
169 File,
171}
172
173#[derive(Debug, Clone, Deserialize, Serialize)]
175#[serde(deny_unknown_fields)]
176pub struct AgentSpec {
177 pub id: String,
179 pub kind: AgentKind,
181 #[serde(default)]
183 pub model: Option<String>,
184 #[serde(default)]
187 pub command: Vec<String>,
188 #[serde(default)]
190 pub extra_args: Vec<String>,
191 #[serde(default)]
193 pub env: BTreeMap<String, String>,
194 #[serde(default)]
196 pub prompt_delivery: Option<Delivery>,
197 #[serde(default, skip_serializing_if = "Option::is_none")]
200 pub max_turn_secs: Option<u64>,
201}
202
203impl AgentSpec {
204 pub fn turn_timeout(&self, budget: std::time::Duration) -> std::time::Duration {
206 self.max_turn_secs.map_or(budget, |secs| {
207 budget.min(std::time::Duration::from_secs(secs))
208 })
209 }
210
211 pub fn delivery(&self) -> Delivery {
217 self.prompt_delivery.unwrap_or(match self.kind {
218 AgentKind::Claude | AgentKind::Command => Delivery::Stdin,
219 AgentKind::Codex => Delivery::Stdin,
223 AgentKind::Omp => Delivery::Stdin,
227 AgentKind::Opencode | AgentKind::Antigravity => Delivery::File,
228 })
229 }
230
231 pub fn display(&self) -> String {
233 match &self.model {
234 Some(m) => format!("{} ({}:{m})", self.id, self.kind.as_str()),
235 None => format!("{} ({})", self.id, self.kind.as_str()),
236 }
237 }
238}
239
240#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
247#[serde(untagged)]
248pub enum AgentChoice {
249 One(String),
251 Chain(Vec<String>),
253}
254
255impl AgentChoice {
256 pub fn ids(&self) -> Vec<&str> {
258 let all: Vec<&str> = match self {
259 Self::One(id) => vec![id.as_str()],
260 Self::Chain(ids) => ids.iter().map(String::as_str).collect(),
261 };
262 all.into_iter()
263 .map(str::trim)
264 .filter(|id| !id.is_empty())
265 .collect()
266 }
267
268 pub fn primary(&self) -> Option<&str> {
270 self.ids().into_iter().next()
271 }
272}
273
274impl From<&str> for AgentChoice {
275 fn from(id: &str) -> Self {
276 Self::One(id.to_owned())
277 }
278}
279
280pub fn primary(choice: Option<&AgentChoice>) -> Option<&str> {
282 choice.and_then(AgentChoice::primary)
283}
284
285#[derive(Debug, Clone, Default, Deserialize, Serialize)]
288#[serde(deny_unknown_fields, default)]
289pub struct Roles {
290 pub implementers: Vec<String>,
292 pub judges: Vec<String>,
294 pub reviewers: Vec<String>,
296 pub fixer: Option<AgentChoice>,
305 pub chatter: Option<AgentChoice>,
319 pub dupes_judge: Option<AgentChoice>,
323 pub conductor: Option<AgentChoice>,
336 pub advisors: Vec<String>,
347 pub synthesizer: Option<AgentChoice>,
360 pub language_judge: Option<AgentChoice>,
369}
370
371#[derive(Debug, Clone, Deserialize, Serialize)]
373#[serde(deny_unknown_fields, default)]
374pub struct Graph {
375 #[serde(rename = "editing_network", skip_serializing)]
379 pub retired_editing_network: Option<serde::de::IgnoredAny>,
380 pub github_text_guard: bool,
382 pub github_language: String,
388 #[serde(alias = "candidates")]
420 pub implementers: usize,
421 #[serde(default)]
423 pub selected_implementer: Option<String>,
424 pub judges: usize,
426 pub deliberate_rounds: usize,
428 pub reviewers: usize,
436 pub review_rounds: usize,
438 pub gate_fix_rounds: usize,
444 pub max_parallel: usize,
446 pub language: String,
448 pub sessions: bool,
456 pub timeout_implement: u64,
458 pub timeout_judge: u64,
460 pub timeout_review: u64,
462 pub timeout_verify: Option<u64>,
471 pub timeout_fix: u64,
473 pub timeout_talk: u64,
481 pub timeout_resource_wait: u64,
490 pub retries: usize,
492 pub worktree_root: Option<PathBuf>,
494 pub land: bool,
507 pub land_rounds: usize,
509 pub rerun_flaky_checks: bool,
517 pub land_approval: bool,
528 pub hold_contested_merge: bool,
539 pub question_routing: bool,
542 pub file_followups: bool,
549 pub release_deputy_followups: bool,
557 pub answer_timeout: u64,
561 pub incomplete_review: IncompleteReviewPolicy,
564 pub e2e_every_round: bool,
582 pub rerun_failed_e2e: bool,
594 pub advise: bool,
608 pub advisors: usize,
613 pub graft_runner_up: bool,
622}
623
624impl Default for Graph {
625 fn default() -> Self {
626 Self {
627 github_text_guard: true,
628 github_language: "en".into(),
629 implementers: 1,
630 selected_implementer: None,
631 retired_editing_network: None,
632 judges: 3,
633 deliberate_rounds: 1,
634 reviewers: 3,
635 review_rounds: 6,
636 gate_fix_rounds: 1,
637 max_parallel: 4,
638 language: "en".to_owned(),
639 sessions: true,
640 timeout_implement: 3600,
641 timeout_judge: 1200,
642 timeout_review: 1200,
643 timeout_verify: None,
644 timeout_fix: 1800,
645 timeout_talk: 3600,
646 timeout_resource_wait: 1800,
647 retries: 1,
648 worktree_root: None,
649 land: true,
650 land_rounds: 4,
651 rerun_flaky_checks: true,
652 land_approval: true,
653 hold_contested_merge: true,
654 question_routing: true,
655 file_followups: true,
656 release_deputy_followups: true,
657 answer_timeout: 86_400,
658 incomplete_review: IncompleteReviewPolicy::Block,
659 e2e_every_round: false,
660 rerun_failed_e2e: true,
661 advise: true,
662 advisors: 3,
663 graft_runner_up: true,
664 }
665 }
666}
667
668impl Graph {
669 pub fn verify_timeout(&self) -> u64 {
673 self.timeout_verify.unwrap_or(self.timeout_review)
674 }
675
676 pub fn language_gate(&self) -> bool {
679 self.github_text_guard && self.github_english()
680 }
681
682 pub fn github_english(&self) -> bool {
684 crate::lang::is_english(&self.github_language)
685 }
686}
687
688#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
695#[serde(rename_all = "lowercase")]
696pub enum IncompleteReviewPolicy {
697 Block,
701 Warn,
706}
707
708#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
710#[serde(rename_all = "lowercase")]
711pub enum LeakPolicy {
712 Warn,
714 Redact,
716 Fail,
718}
719
720#[derive(Debug, Clone, Deserialize, Serialize)]
727#[serde(deny_unknown_fields, default)]
728pub struct Blind {
729 pub commit_msg_hook: bool,
732 pub strip_lines: Vec<String>,
736 pub vendor_tokens: Vec<String>,
738 pub on_leak: LeakPolicy,
740 pub seed: Option<u64>,
743}
744
745impl Default for Blind {
746 fn default() -> Self {
747 Self {
748 commit_msg_hook: true,
749 strip_lines: [
750 "Co-Authored-By:",
751 "Signed-off-by:",
752 "Assisted-by:",
753 "Generated-by:",
754 "Generated with",
755 "\u{1f916}",
756 ]
757 .iter()
758 .map(|s| (*s).to_owned())
759 .collect(),
760 vendor_tokens: [
761 "claude",
762 "anthropic",
763 "codex",
764 "openai",
765 "chatgpt",
766 "gemini",
767 "grok",
768 "xai",
769 "copilot",
770 "opencode",
771 "qoder",
772 "cursor",
773 "\u{1f916}",
774 ]
775 .iter()
776 .map(|s| (*s).to_owned())
777 .collect(),
778 on_leak: LeakPolicy::Warn,
779 seed: None,
780 }
781 }
782}
783
784#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize, clap::ValueEnum)]
786#[serde(rename_all = "snake_case")]
787pub enum BuildCache {
788 #[default]
790 Shared,
791 Isolated,
793}
794
795impl std::fmt::Display for BuildCache {
796 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
797 f.write_str(match self {
798 Self::Shared => "shared",
799 Self::Isolated => "isolated",
800 })
801 }
802}
803
804#[derive(Debug, Clone, Default, Deserialize, Serialize)]
806#[serde(deny_unknown_fields, default)]
807pub struct Verify {
808 pub build_cache: BuildCache,
810 pub e2e: Vec<String>,
813 pub gate: Vec<String>,
815 #[serde(default)]
826 pub pre_gate: Vec<String>,
827 pub shell: Option<Vec<String>>,
830}
831
832impl Verify {
833 pub fn cache_dir(&self) -> Option<PathBuf> {
839 self.e2e
840 .iter()
841 .chain(self.gate.iter())
842 .find_map(|cmd| crate::disk::extract_cargo_target_dir(cmd))
843 }
844
845 pub fn cargo_manifests(&self) -> Vec<PathBuf> {
848 let all: Vec<String> = self.e2e.iter().chain(self.gate.iter()).cloned().collect();
849 crate::cache::extract_manifest_paths(&all)
850 }
851}
852
853#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
855#[serde(deny_unknown_fields, default)]
856pub struct Worktree {
857 pub setup: Vec<SetupStep>,
860 pub pre_clean: Vec<PreCleanStep>,
862}
863
864#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
866#[serde(deny_unknown_fields)]
867pub struct PreCleanStep {
868 pub run: String,
870 pub timeout_secs: Option<u64>,
872}
873
874#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
876#[serde(deny_unknown_fields, default)]
877pub struct SetupStep {
878 pub copy: Option<String>,
881 pub optional: bool,
883 pub run: Option<String>,
885 pub timeout_secs: Option<u64>,
888}
889
890impl Worktree {
891 pub fn validate(&self) -> Result<()> {
893 for (i, step) in self.pre_clean.iter().enumerate() {
894 if step.run.trim().is_empty() || step.timeout_secs == Some(0) {
895 bail!(
896 "[worktree] pre_clean step {} requires a nonempty run and positive timeout",
897 i + 1
898 );
899 }
900 }
901 for (i, step) in self.setup.iter().enumerate() {
902 let n = i + 1;
903 match (&step.copy, &step.run) {
904 (Some(c), None) => {
905 if step.timeout_secs.is_some() {
906 bail!("[worktree] setup step {n}: `timeout_secs` applies to `run` only");
907 }
908 crate::worktree_setup::validate_copy(c)
909 .with_context(|| format!("[worktree] setup step {n}"))?;
910 }
911 (None, Some(r)) => {
912 if r.trim().is_empty() {
913 bail!("[worktree] setup step {n}: `run` is empty");
914 }
915 if step.optional {
916 bail!("[worktree] setup step {n}: `optional` applies to `copy` only");
917 }
918 }
919 _ => bail!("[worktree] setup step {n} must set exactly one of `copy` and `run`"),
920 }
921 }
922 Ok(())
923 }
924}
925
926#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
936#[serde(deny_unknown_fields, default)]
937pub struct Disk {
938 pub min_free_bytes: u64,
947 pub auto_fold: bool,
953 pub fold_grace_secs: u64,
961 pub cache_limit_bytes: u64,
973 pub worktree_limit_bytes: u64,
975 pub worktree_reclaim_bytes: u64,
979 pub retained_attempt_limit: usize,
983}
984
985impl Default for Disk {
986 fn default() -> Self {
987 Self {
988 min_free_bytes: 8 * 1024 * 1024 * 1024,
989 auto_fold: true,
990 fold_grace_secs: 6 * 60 * 60,
991 cache_limit_bytes: 10 * 1024 * 1024 * 1024,
992 worktree_limit_bytes: 10 * 1024 * 1024 * 1024,
993 worktree_reclaim_bytes: 16 * 1024 * 1024 * 1024,
994 retained_attempt_limit: 8,
995 }
996 }
997}
998
999#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1001#[serde(rename_all = "lowercase")]
1002pub enum MergeMode {
1003 None,
1006 Local,
1009 Pr,
1013}
1014
1015#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
1029#[serde(rename_all = "lowercase")]
1030pub enum MergeStyle {
1031 #[default]
1036 Merge,
1037 Squash,
1043 Rebase,
1049}
1050
1051#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1053#[serde(rename_all = "lowercase")]
1054pub enum MergeCi {
1055 #[default]
1057 Expected,
1058 None,
1060}
1061
1062impl MergeCi {
1063 pub fn expectation(self) -> crate::land::CiExpectation {
1065 match self {
1066 Self::Expected => crate::land::CiExpectation::Expected,
1067 Self::None => crate::land::CiExpectation::Absent,
1068 }
1069 }
1070}
1071
1072#[derive(Debug, Clone, Deserialize, Serialize)]
1074#[serde(deny_unknown_fields, default)]
1075pub struct Merge {
1076 pub mode: MergeMode,
1079 pub ci: MergeCi,
1081 pub base: Option<String>,
1083 pub style: MergeStyle,
1086 pub remote: String,
1088 pub release_bump: bool,
1101}
1102
1103impl Default for Merge {
1104 fn default() -> Self {
1105 Self {
1106 mode: MergeMode::None,
1107 ci: MergeCi::Expected,
1108 base: None,
1109 style: MergeStyle::default(),
1110 remote: "origin".to_owned(),
1111 release_bump: true,
1112 }
1113 }
1114}
1115
1116#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1118#[serde(rename_all = "lowercase")]
1119pub enum UpdateMode {
1120 Off,
1122 Notify,
1125 Install,
1127}
1128
1129#[derive(Debug, Clone, Deserialize, Serialize)]
1131#[serde(deny_unknown_fields, default)]
1132pub struct Update {
1133 pub mode: UpdateMode,
1135 pub interval: Option<String>,
1137 pub auto_restart: bool,
1139}
1140
1141impl Default for Update {
1142 fn default() -> Self {
1143 Self {
1144 mode: UpdateMode::Notify,
1145 interval: None,
1146 auto_restart: false,
1147 }
1148 }
1149}
1150
1151#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1153#[serde(rename_all = "lowercase")]
1154pub enum ReleaseMode {
1155 #[default]
1158 Actions,
1159 Local,
1164}
1165
1166#[derive(Debug, Clone, Deserialize, Serialize)]
1168#[serde(deny_unknown_fields, default)]
1169pub struct Release {
1170 pub mode: ReleaseMode,
1173 pub commands: Vec<String>,
1180 pub timeout_minutes: u64,
1182 pub version_files: Vec<VersionFile>,
1190}
1191
1192#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1194#[serde(rename_all = "lowercase")]
1195pub enum VersionKind {
1196 Cargo,
1198 Json,
1200}
1201
1202#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
1204#[serde(deny_unknown_fields)]
1205pub struct VersionFile {
1206 pub path: String,
1208 pub kind: VersionKind,
1210}
1211
1212impl Default for Release {
1213 fn default() -> Self {
1214 Self {
1215 mode: ReleaseMode::Actions,
1216 commands: Vec::new(),
1217 timeout_minutes: 30,
1218 version_files: Vec::new(),
1219 }
1220 }
1221}
1222
1223impl Release {
1224 pub fn validate(&self) -> Result<()> {
1226 crate::release_manifest::validate(&self.version_files).context("[release] version_files")
1227 }
1228
1229 pub fn is_local(&self) -> bool {
1231 self.mode == ReleaseMode::Local
1232 }
1233}
1234
1235#[derive(Debug, Clone, Deserialize, Serialize)]
1237#[serde(try_from = "CoordinationFields")]
1238pub struct Coordination {
1239 pub contract_file: String,
1241 pub contract_token: String,
1243 pub lock_file: String,
1245}
1246
1247#[derive(Deserialize, Default)]
1248#[serde(deny_unknown_fields, default)]
1249struct CoordinationFields {
1250 contract_file: String,
1251 contract_token: String,
1252 lock_file: String,
1253}
1254
1255impl TryFrom<CoordinationFields> for Coordination {
1256 type Error = anyhow::Error;
1257
1258 fn try_from(fields: CoordinationFields) -> Result<Self> {
1259 for (key, name) in [
1260 ("coordination.contract_file", &fields.contract_file),
1261 ("coordination.lock_file", &fields.lock_file),
1262 ] {
1263 if name.trim().is_empty()
1264 || name != name.trim()
1265 || name == "."
1266 || name.contains("..")
1267 || name.contains(['/', '\\', ':', '\0'])
1268 {
1269 bail!(
1270 "{key} must be a plain file name inside the Git common directory (no separators or '..')"
1271 );
1272 }
1273 }
1274 let token = &fields.contract_token;
1275 if token.is_empty() || token.trim() != token || token.chars().any(char::is_control) {
1276 bail!(
1277 "coordination.contract_token must be a nonempty single-line token without surrounding whitespace"
1278 );
1279 }
1280 Ok(Self {
1281 contract_file: fields.contract_file,
1282 contract_token: fields.contract_token,
1283 lock_file: fields.lock_file,
1284 })
1285 }
1286}
1287
1288#[cfg(test)]
1289pub(crate) fn test_coordination() -> Option<Coordination> {
1290 Some(Coordination {
1291 contract_file: "updater.contract".into(),
1292 contract_token: "test-protocol-v1".into(),
1293 lock_file: "updater.lock".into(),
1294 })
1295}
1296
1297#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1299#[serde(deny_unknown_fields, default)]
1300pub struct Config {
1301 pub coordination: Option<Coordination>,
1303 pub agents: Vec<AgentSpec>,
1305 pub roles: Roles,
1307 pub graph: Graph,
1309 pub blind: Blind,
1311 pub verify: Verify,
1313 pub worktree: Worktree,
1315 pub disk: Disk,
1317 pub merge: Merge,
1319 pub update: Update,
1321 pub prompts: Prompts,
1323 pub notify: Notify,
1325 pub repos: Repos,
1328 pub talk: Talk,
1330 pub daemon: Daemon,
1332 pub release: Release,
1334 pub context_windows: BTreeMap<String, u64>,
1337}
1338
1339const BUILTIN_CONTEXT_WINDOWS: &[(&str, u64)] = &[
1349 ("claude-opus-4", 200_000),
1350 ("claude-sonnet-4", 200_000),
1351 ("claude-haiku-4", 200_000),
1352 ("claude-3", 200_000),
1353 ("opus", 200_000),
1354 ("sonnet", 200_000),
1355 ("haiku", 200_000),
1356 ("gpt-5", 400_000),
1357 ("gpt-4.1", 1_000_000),
1358 ("gpt-4o", 128_000),
1359 ("o3", 200_000),
1360 ("o4-mini", 200_000),
1361 ("gemini-2.5", 1_000_000),
1362 ("deepseek", 128_000),
1363];
1364
1365impl Config {
1366 pub fn context_window(&self, model: &str) -> Option<u64> {
1371 fn lookup<'a>(model: &str, entries: impl Iterator<Item = (&'a str, u64)>) -> Option<u64> {
1372 let mut best: Option<(usize, u64)> = None;
1373 for (key, window) in entries {
1374 if key == model {
1375 return Some(window);
1376 }
1377 if model.starts_with(key) && best.is_none_or(|(len, _)| key.len() > len) {
1378 best = Some((key.len(), window));
1379 }
1380 }
1381 best.map(|(_, w)| w)
1382 }
1383 lookup(
1384 model,
1385 self.context_windows.iter().map(|(k, w)| (k.as_str(), *w)),
1386 )
1387 .or_else(|| lookup(model, BUILTIN_CONTEXT_WINDOWS.iter().copied()))
1388 }
1389}
1390
1391#[derive(Debug, Clone, Deserialize, Serialize)]
1401#[serde(deny_unknown_fields, default)]
1402pub struct Daemon {
1403 pub max_concurrent_runs: usize,
1424 pub pause_for_interrupts: bool,
1440 pub max_deputies: usize,
1447 pub release_stall_minutes: u64,
1454}
1455
1456impl Default for Daemon {
1457 fn default() -> Self {
1458 Self {
1459 max_concurrent_runs: 1,
1460 pause_for_interrupts: false,
1461 max_deputies: 2,
1462 release_stall_minutes: 60,
1463 }
1464 }
1465}
1466
1467#[derive(Debug, Clone, Deserialize, Serialize)]
1479#[serde(deny_unknown_fields, default)]
1480pub struct Repos {
1481 pub roots: Vec<PathBuf>,
1485 pub auto_clone: bool,
1487 pub clone_command: Option<Vec<String>>,
1491 pub scan_ttl: u64,
1498 pub fetch_interval: u64,
1503}
1504
1505impl Default for Repos {
1506 fn default() -> Self {
1507 Self {
1508 roots: Vec::new(),
1509 auto_clone: false,
1510 clone_command: None,
1511 scan_ttl: 86_400,
1512 fetch_interval: 600,
1513 }
1514 }
1515}
1516
1517#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1533#[serde(deny_unknown_fields, default)]
1534pub struct Prompts {
1535 pub all: String,
1537 pub implement: String,
1539 pub judge: String,
1541 pub review: String,
1543 pub fix: String,
1545}
1546
1547impl Prompts {
1548 pub fn overlay(&self, node: &str) -> Option<String> {
1553 let specific = match node {
1554 "implement" => &self.implement,
1555 "judge" | "vote" | "deliberate" => &self.judge,
1556 "review" => &self.review,
1557 "fix" => &self.fix,
1558 _ => "",
1559 };
1560 let mut parts: Vec<&str> = Vec::new();
1561 for p in [self.all.trim(), specific.trim()] {
1562 if !p.is_empty() {
1563 parts.push(p);
1564 }
1565 }
1566 if parts.is_empty() {
1567 return None;
1568 }
1569 Some(parts.join("\n\n"))
1570 }
1571}
1572
1573#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1580#[serde(deny_unknown_fields, default)]
1581pub struct Notify {
1582 pub command: Vec<String>,
1585}
1586
1587#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1589#[serde(deny_unknown_fields, default)]
1590pub struct Talk {
1591 pub allow_write: bool,
1600 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1602 pub standing_authorization: bool,
1603 pub personas: Vec<PersonaSpec>,
1608 pub operator_name: Option<String>,
1612}
1613
1614pub const OPERATOR_NAME_MAX: usize = 64;
1616
1617impl Talk {
1618 pub fn operator_name(&self) -> Option<&str> {
1620 self.operator_name
1621 .as_deref()
1622 .map(str::trim)
1623 .filter(|n| !n.is_empty())
1624 }
1625}
1626
1627#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
1629#[serde(deny_unknown_fields)]
1630pub struct PersonaSpec {
1631 pub id: String,
1633 #[serde(default)]
1636 pub name: String,
1637 #[serde(default)]
1640 pub prompt: String,
1641 #[serde(default, skip_serializing_if = "Option::is_none")]
1645 pub icon: Option<String>,
1646}
1647
1648#[derive(Debug, Clone)]
1650pub struct ResolvedRoles {
1651 pub implementers: Vec<AgentSpec>,
1653 pub judges: Vec<AgentSpec>,
1655 pub reviewers: Vec<AgentSpec>,
1657 pub fixer: Option<Vec<AgentSpec>>,
1662 pub conductor: AgentSpec,
1664 pub implementer_roster: Vec<AgentSpec>,
1672 pub judge_roster: Vec<AgentSpec>,
1676 pub reviewer_roster: Vec<AgentSpec>,
1678}
1679
1680fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
1687 let mut out = Vec::new();
1688 for (k, v) in table {
1689 if prefix.is_empty() && k == "vars" {
1690 continue;
1691 }
1692 let path = if prefix.is_empty() {
1693 k.clone()
1694 } else {
1695 format!("{prefix}.{k}")
1696 };
1697 match v {
1698 toml::Value::Array(_) => out.push(path),
1699 toml::Value::Table(t) => out.extend(array_keys(t, &path)),
1700 _ => {}
1701 }
1702 }
1703 out
1704}
1705
1706#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1708enum ArrayMerge {
1709 Append,
1713 Replace,
1716}
1717
1718fn array_merge_policy(key: &str) -> ArrayMerge {
1757 match key {
1758 "verify.e2e" | "verify.gate" | "verify.pre_gate" | "repos.roots" => ArrayMerge::Append,
1759 _ => ArrayMerge::Replace,
1760 }
1761}
1762
1763impl Config {
1764 pub fn load(path: &Path) -> Result<Self> {
1767 Self::load_layers(&[path.to_path_buf()])
1768 }
1769
1770 fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
1780 let mut ctx = teravars::system_context();
1781 let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
1782 ctx.insert("env", &env);
1783 if let Some(last) = paths.last()
1784 && let Some(dir) = last.parent()
1785 {
1786 let dir = std::fs::read_to_string(dir.join(REPO_MARKER))
1789 .map(|s| PathBuf::from(s.trim()))
1790 .unwrap_or_else(|_| dir.to_path_buf());
1791 ctx.insert("repo", &dir.to_string_lossy());
1792 ctx.insert(
1793 "repo_name",
1794 &dir.file_name().unwrap_or_default().to_string_lossy(),
1795 );
1796 }
1797 ctx
1798 }
1799
1800 pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
1808 Self::load_layers_with_machine(paths, Self::machine_layer())
1809 }
1810
1811 fn load_layers_with_machine(paths: &[PathBuf], machine: Option<PathBuf>) -> Result<Self> {
1812 let mut engine = teravars::Engine::default();
1813 let ctx = Self::render_ctx(paths);
1814 if paths.len() > 1 {
1815 Self::refuse_split_arrays(paths, &mut engine, &ctx).map_err(|error| {
1816 if error.downcast_ref::<ConfigFailure>().is_some() {
1817 error
1818 } else {
1819 let message = error.to_string();
1822 error
1823 .context(ConfigFailure::layers("config-merge", paths))
1824 .context(message)
1825 }
1826 })?;
1827 }
1828 let merged = teravars::load_merged(paths, &mut engine, &ctx)
1829 .map_err(|error| {
1830 let cause = ConfigFailure::render(&error, paths);
1831 anyhow::Error::new(error).context(cause)
1832 })
1833 .with_context(|| {
1834 format!(
1835 "rendering config via teravars: {}",
1836 paths
1837 .iter()
1838 .map(|p| p.display().to_string())
1839 .collect::<Vec<_>>()
1840 .join(", ")
1841 )
1842 })?;
1843 let mut table = merged.config;
1844 Self::normalize_renamed_keys(paths, &mut engine, &ctx, &mut table)?;
1845 let standing = table
1848 .get_mut("talk")
1849 .and_then(toml::Value::as_table_mut)
1850 .and_then(|talk| talk.remove("standing_authorization"));
1851 let standing = if standing.is_some()
1852 && let Some(machine) = machine.filter(|machine| paths.contains(machine))
1853 {
1854 let machine_paths = [machine];
1855 let mut engine = teravars::Engine::default();
1856 let layer = teravars::load_merged(
1857 &machine_paths,
1858 &mut engine,
1859 &Self::render_ctx(&machine_paths),
1860 )
1861 .context("read machine standing authorization")?;
1862 layer
1863 .config
1864 .get("talk")
1865 .and_then(|talk| talk.get("standing_authorization"))
1866 .map(|value| {
1867 value.as_bool().context(
1868 "[talk] standing_authorization in the machine layer must be a boolean",
1869 )
1870 })
1871 .transpose()?
1872 .unwrap_or(false)
1873 } else {
1874 false
1875 };
1876 table.remove("vars");
1879 let detect_agents = !table.contains_key("agents");
1883 let mut cfg: Self = toml::Value::Table(table)
1884 .try_into()
1885 .context("deserializing magi config")
1886 .context(ConfigFailure::layers("config-deserialize", paths))?;
1887 cfg.talk.standing_authorization = standing;
1888 if !cfg.graph.question_routing {
1889 tracing::warn!(
1890 "[graph] question_routing is retired and ignored; task inquiries always use their chat"
1891 );
1892 }
1893 crate::persona::validate(&cfg.talk.personas)?;
1894 cfg.worktree.validate()?;
1895 cfg.release.validate()?;
1896 if let Some(name) = cfg.talk.operator_name() {
1897 if name.chars().count() > OPERATOR_NAME_MAX || name.chars().any(char::is_control) {
1898 bail!(
1899 "[talk] operator_name must be one line of at most {OPERATOR_NAME_MAX} characters"
1900 );
1901 }
1902 }
1903 if detect_agents {
1904 cfg.agents = Self::autodetected().agents;
1905 }
1906 Ok(cfg)
1907 }
1908
1909 fn normalize_renamed_keys(
1917 paths: &[PathBuf],
1918 engine: &mut teravars::Engine,
1919 ctx: &teravars::Context,
1920 table: &mut toml::map::Map<String, toml::Value>,
1921 ) -> Result<()> {
1922 let both = matches!(
1923 table.get("graph"),
1924 Some(toml::Value::Table(g)) if g.contains_key("candidates") && g.contains_key("implementers")
1925 );
1926 if !both {
1927 return Ok(());
1928 }
1929 let mut winner: Option<toml::Value> = None;
1930 for path in paths {
1931 let one = teravars::load_merged([path], engine, ctx)
1932 .map_err(|error| {
1933 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
1934 anyhow::Error::new(error).context(cause)
1935 })
1936 .with_context(|| format!("rendering {}", path.display()))?;
1937 let Some(toml::Value::Table(g)) = one.config.get("graph") else {
1938 continue;
1939 };
1940 if g.contains_key("candidates") && g.contains_key("implementers") {
1941 bail!(
1942 "`[graph]` sets both `implementers` and its deprecated alias \n `candidates` in {}; keep only `implementers`.",
1943 path.display()
1944 );
1945 }
1946 if let Some(v) = g.get("implementers").or_else(|| g.get("candidates")) {
1947 winner = Some(v.clone());
1948 }
1949 }
1950 if let Some(toml::Value::Table(g)) = table.get_mut("graph") {
1951 g.remove("candidates");
1952 if let Some(v) = winner {
1953 g.insert("implementers".to_owned(), v);
1954 }
1955 }
1956 Ok(())
1957 }
1958
1959 fn refuse_split_arrays(
1983 paths: &[PathBuf],
1984 engine: &mut teravars::Engine,
1985 ctx: &teravars::Context,
1986 ) -> Result<()> {
1987 let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
1988 for path in paths {
1989 let one = teravars::load_merged([path], engine, ctx)
1990 .map_err(|error| {
1991 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
1992 anyhow::Error::new(error).context(cause)
1993 })
1994 .with_context(|| format!("rendering {}", path.display()))?;
1995 for key in array_keys(&one.config, "") {
1996 if array_merge_policy(&key) == ArrayMerge::Append {
1997 continue;
1998 }
1999 if let Some(first) = seen.get(&key) {
2000 bail!(
2001 "`{key}` is an array declared in two config layers:\n \
2002 {}\n {}\nteravars appends arrays when it merges, so \
2003 magi would run the concatenation of both - which is \
2004 not what either file says. Declare `{key}` in exactly \
2005 one of them.",
2006 first.display(),
2007 path.display()
2008 );
2009 }
2010 seen.insert(key, path.clone());
2011 }
2012 }
2013 Ok(())
2014 }
2015
2016 pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
2038 let mut engine = teravars::Engine::default();
2039 let ctx = Self::render_ctx(paths);
2040 let mut out = Vec::new();
2041 for path in paths {
2042 let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
2043 continue;
2044 };
2045 let mut cur = &one.config;
2046 let mut found = None;
2047 let parts: Vec<&str> = key.split('.').collect();
2048 for (i, part) in parts.iter().enumerate() {
2049 match cur.get(*part) {
2050 Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
2051 found = Some(a);
2052 break;
2053 }
2054 Some(toml::Value::Table(t)) => cur = t,
2055 _ => break,
2056 }
2057 }
2058 let Some(values) = found else { continue };
2059 let strings: Vec<String> = values
2060 .iter()
2061 .filter_map(|v| v.as_str().map(str::to_owned))
2062 .collect();
2063 if !strings.is_empty() {
2064 out.push((path.clone(), strings));
2065 }
2066 }
2067 out
2068 }
2069
2070 pub(crate) fn layer_tables(paths: &[PathBuf]) -> Vec<(PathBuf, Result<toml::Table>)> {
2076 let mut engine = teravars::Engine::default();
2077 let ctx = Self::render_ctx(paths);
2078 paths
2079 .iter()
2080 .map(|path| {
2081 let one = teravars::load_merged([path], &mut engine, &ctx)
2082 .map(|m| m.config)
2083 .with_context(|| format!("rendering {}", path.display()));
2084 (path.clone(), one)
2085 })
2086 .collect()
2087 }
2088
2089 pub fn describe_composed(
2099 paths: &[PathBuf],
2100 commands: &[String],
2101 key: &str,
2102 empty: &str,
2103 ) -> String {
2104 if commands.is_empty() {
2105 return empty.to_owned();
2106 }
2107 let joined = commands.join(" && ");
2108 let provenance = Self::array_provenance(paths, key);
2109 if provenance.len() <= 1 {
2110 return joined;
2111 }
2112 let mut out = joined;
2113 for (path, cmds) in &provenance {
2114 out.push_str(&format!("\n [{}] {}", path.display(), cmds.join(" && ")));
2115 }
2116 out
2117 }
2118
2119 pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
2126 #[cfg(test)]
2127 crate::web::request_cost::discovery();
2128 if let Some(p) = explicit {
2129 let paths = vec![p.to_path_buf()];
2130 return Ok((Self::load_layers(&paths)?, paths));
2131 }
2132 let paths = Self::layers_checked(repo)?;
2133 if paths.is_empty() {
2134 return Ok((Self::autodetected(), paths));
2135 }
2136 Ok((Self::load_layers(&paths)?, paths))
2137 }
2138
2139 pub async fn discover_fetched(
2142 repo: &Path,
2143 explicit: Option<&Path>,
2144 ) -> Result<(Self, Vec<PathBuf>)> {
2145 if explicit.is_none() && is_git_worktree(repo) {
2146 let (remote, cfg_base) = probe_remote_base(repo);
2150 let base = crate::git::merge_base_branch(repo, &remote, cfg_base.as_deref())
2151 .await
2152 .with_context(|| ConfigFailure {
2153 stage: "config-base",
2154 target: remote.clone(),
2155 })?;
2156 let out = crate::git::fetch(repo, &remote, &base)
2157 .await
2158 .with_context(|| format!("fetching {remote}/{base} to read magi.toml"))
2159 .with_context(|| ConfigFailure {
2160 stage: "config-fetch",
2161 target: format!("{remote}/{base}"),
2162 })?;
2163 if !out.ok() {
2164 return Err(anyhow::anyhow!(
2165 "cannot read magi.toml: `git fetch {remote} {base}` failed ({}); refusing to use the local checkout's copy, which may be stale",
2166 out.stderr.lines().next().unwrap_or("").trim()
2167 )).context(ConfigFailure { stage: "config-fetch", target: format!("{remote}/{base}") });
2168 }
2169 if cfg_base.is_none() {
2170 crate::git::ensure_remote_head(repo, &remote, &base).await;
2171 }
2172 }
2173 Self::discover(repo, explicit).map_err(|error| {
2174 if error.downcast_ref::<ConfigFailure>().is_some() {
2175 error
2176 } else {
2177 error.context(ConfigFailure {
2178 stage: "config-load",
2179 target: explicit.unwrap_or(repo).to_string_lossy().into_owned(),
2180 })
2181 }
2182 })
2183 }
2184
2185 fn layers_checked(repo: &Path) -> Result<Vec<PathBuf>> {
2187 if !is_git_worktree(repo) {
2188 return Ok(Self::layers(repo));
2189 }
2190 let mut paths: Vec<PathBuf> = Self::machine_layer()
2191 .into_iter()
2192 .filter(|p| p.is_file())
2193 .collect();
2194 paths.extend(Self::repo_layers(repo)?);
2195 Ok(paths)
2196 }
2197
2198 pub(crate) fn repo_layer_description(repo: &Path, path: &Path) -> String {
2200 let cached = path.ancestors().find(|p| p.join(REPO_MARKER).is_file());
2201 if let Some(root) = cached {
2202 let relative = path.strip_prefix(root).unwrap_or(path);
2203 let reference = resolve_remote_base(repo)
2204 .map(|(remote, base)| format!("{remote}/{base}"))
2205 .unwrap_or_else(|_| "remote base".to_owned());
2206 format!(
2207 "{} at {reference} (including its includes)",
2208 repo.join(relative).display()
2209 )
2210 } else {
2211 format!("{} (including its includes)", path.display())
2212 }
2213 }
2214
2215 pub(crate) fn repo_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2218 if !is_git_worktree(repo) {
2219 return Ok([
2220 repo.join(".magi").join("config.toml"),
2221 repo.join("magi.toml"),
2222 ]
2223 .into_iter()
2224 .filter(|p| p.is_file())
2225 .collect());
2226 }
2227 remote_layers(repo)
2228 }
2229
2230 pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
2250
2251 pub fn layers(repo: &Path) -> Vec<PathBuf> {
2256 let mut paths = Vec::new();
2257 paths.extend(Self::machine_layer());
2258 paths.push(repo.join(".magi").join("config.toml"));
2259 paths.push(repo.join("magi.toml"));
2260 paths.retain(|p| p.is_file());
2261 paths
2262 }
2263
2264 #[cfg(test)]
2271 pub(crate) fn machine_layer() -> Option<PathBuf> {
2272 std::env::var(Self::CONFIG_DIR_ENV)
2273 .ok()
2274 .filter(|dir| !dir.trim().is_empty())
2275 .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
2276 }
2277
2278 #[cfg(not(test))]
2280 pub(crate) fn machine_layer() -> Option<PathBuf> {
2281 match std::env::var(Self::CONFIG_DIR_ENV) {
2282 Ok(dir) if dir.trim().is_empty() => None,
2284 Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
2285 Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
2286 }
2287 }
2288
2289 pub fn autodetected() -> Self {
2291 let mut cfg = Self::default();
2292 for (kind, id, model) in [
2293 (AgentKind::Claude, "opus", Some("opus")),
2294 (AgentKind::Claude, "sonnet", Some("sonnet")),
2295 (AgentKind::Antigravity, "antigravity", None),
2296 (AgentKind::Opencode, "opencode", None),
2297 (AgentKind::Codex, "codex", None),
2298 (AgentKind::Omp, "omp", None),
2299 ] {
2300 if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
2301 cfg.agents.push(AgentSpec {
2302 id: id.to_owned(),
2303 kind,
2304 model: model.map(str::to_owned),
2305 command: Vec::new(),
2306 extra_args: Vec::new(),
2307 env: BTreeMap::new(),
2308 prompt_delivery: None,
2309 max_turn_secs: None,
2310 });
2311 }
2312 }
2313 cfg
2314 }
2315
2316 pub fn cache_dir(&self) -> Option<PathBuf> {
2319 self.verify.cache_dir()
2320 }
2321
2322 pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
2324 self.agents
2325 .iter()
2326 .find(|a| a.id == id)
2327 .with_context(|| format!("no agent with id `{id}` in the roster"))
2328 }
2329
2330 fn rotate(&self, ids: &[String], count: usize, offset: usize) -> Result<Vec<AgentSpec>> {
2337 let mut out = Vec::with_capacity(count);
2338 for i in 0..count {
2339 let spec = if ids.is_empty() {
2340 self.agents[(i + offset) % self.agents.len()].clone()
2341 } else {
2342 self.agent(&ids[i % ids.len()])?.clone()
2343 };
2344 out.push(spec);
2345 }
2346 Ok(out)
2347 }
2348
2349 fn full_roster(&self, ids: &[String]) -> Result<Vec<AgentSpec>> {
2356 if ids.is_empty() {
2357 Ok(self.agents.clone())
2358 } else {
2359 ids.iter().map(|id| self.agent(id).cloned()).collect()
2360 }
2361 }
2362
2363 pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
2370 if self.agents.is_empty() {
2371 bail!(
2372 "agent roster is empty: no agent CLI found on PATH and no \
2373 [[agents]] in the config. Run `magi init` to write a starter \
2374 magi.toml."
2375 );
2376 }
2377 let pinned = self
2378 .graph
2379 .selected_implementer
2380 .as_ref()
2381 .map(|id| self.agent(id).cloned())
2382 .transpose()?;
2383 Ok(ResolvedRoles {
2384 implementers: match &pinned {
2385 Some(agent) => vec![agent.clone()],
2386 None => self.rotate(&self.roles.implementers, self.graph.implementers, 0)?,
2387 },
2388 judges: self.rotate(&self.roles.judges, self.graph.judges, 1)?,
2389 reviewers: self.rotate(&self.roles.reviewers, self.graph.reviewers, 0)?,
2390 fixer: match self.roles.fixer.as_ref() {
2391 Some(choice) => Some(crate::agent::pick_chain(
2394 &self.agents,
2395 Some(choice),
2396 &|_| true,
2397 "fixer",
2398 )?),
2399 None => None,
2400 },
2401 conductor: match self.roles.conductor.as_ref().map(AgentChoice::ids) {
2406 Some(ids) if ids.len() == 1 => self.agent(ids[0])?.clone(),
2407 Some(ids) if !ids.is_empty() => ids
2410 .iter()
2411 .find_map(|id| self.agent(id).ok())
2412 .cloned()
2413 .with_context(|| {
2414 format!("[roles] conductor names no agent in the roster: {ids:?}")
2415 })?,
2416 _ => crate::agent::pick(&self.agents, None, &crate::agent::installed)
2421 .unwrap_or_else(|_| self.agents[0].clone()),
2422 },
2423 implementer_roster: match pinned {
2424 Some(agent) => vec![agent],
2425 None => self.full_roster(&self.roles.implementers)?,
2426 },
2427 judge_roster: self.full_roster(&self.roles.judges)?,
2428 reviewer_roster: self.full_roster(&self.roles.reviewers)?,
2429 })
2430 }
2431
2432 pub fn advisors(&self) -> Result<Vec<AgentSpec>> {
2454 if self.agents.is_empty() {
2455 bail!(
2456 "agent roster is empty: no agent CLI found on PATH and no \
2457 [[agents]] in the config. Run `magi init` to write a starter \
2458 magi.toml."
2459 );
2460 }
2461 if !self.roles.advisors.is_empty() {
2462 return self.rotate(&self.roles.advisors, self.graph.advisors, 0);
2463 }
2464 self.rotate(&self.roles.judges, self.graph.advisors, 1)
2465 }
2466
2467 pub fn advisor_roster(&self) -> Result<Vec<AgentSpec>> {
2471 if self.roles.advisors.is_empty() {
2472 self.full_roster(&self.roles.judges)
2473 } else {
2474 self.full_roster(&self.roles.advisors)
2475 }
2476 }
2477
2478 pub fn shell(&self) -> Vec<String> {
2480 if let Some(s) = &self.verify.shell {
2481 return s.clone();
2482 }
2483 if which("sh") {
2484 vec!["sh".to_owned(), "-c".to_owned()]
2485 } else {
2486 vec!["cmd".to_owned(), "/C".to_owned()]
2487 }
2488 }
2489
2490 pub fn starter_toml() -> String {
2492 let detected = Self::autodetected();
2493 let mut s = String::from(
2494 "# magi — blind multi-agent implementation competition.\n\
2495 # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
2496 # -> blind judging -> deliberation -> private final vote\n\
2497 # -> fold losers -> review + E2E loop -> gate -> merge.\n\
2498 #\n\
2499 # Rendered by teravars: a `[vars]` table, env\n\
2500 # and system lookups, and `include = [...]` all work. Tera\n\
2501 # braces are live everywhere in this file, but comments are\n\
2502 # stripped before rendering (teravars >= 0.2.2), so a comment\n\
2503 # may quote `{{ ... }}` freely.\n\
2504 #\n\
2505 # Layers deep-merge in increasing\n\
2506 # precedence, so the roster can live once per machine in\n\
2507 # <config_dir>/magi/config.toml and each repo only states its own\n\
2508 # gate:\n\
2509 # <config_dir>/magi/config.toml < .magi/config.toml < magi.toml\n\n\
2510 [vars]\n\
2511 # Reference it as vars.cache inside Tera braces, anywhere below.\n\
2512 # Single quotes inside the braces: teravars renders the raw file\n\
2513 # text, so TOML's own \\\" escaping never reaches Tera.\n\
2514 cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
2515 );
2516 if detected.agents.is_empty() {
2517 s.push_str(
2518 "# No agent CLI was found on PATH. Fill this in by hand.\n\
2519 # kind = claude | opencode | antigravity | codex | command\n\
2520 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
2521 );
2522 } else {
2523 for a in &detected.agents {
2524 s.push_str("[[agents]]\n");
2525 s.push_str(&format!("id = {:?}\n", a.id));
2526 s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
2527 if let Some(m) = &a.model {
2528 s.push_str(&format!("model = {m:?}\n"));
2529 }
2530 s.push('\n');
2531 }
2532 }
2533 s.push_str(
2534 "# Leave a role list empty to rotate through the roster.\n\
2535 # A non-empty list is also an ordered backup list: seats take entries from the\n\
2536 # front (see [graph] counts) and a failed or out-of-quota seat moves on to the\n\
2537 # next agent to its right, each tried once. Same for judges and reviewers.\n\
2538 # implementers = [\"opus\", \"codex\", \"sonnet\"] # with implementers = 1 below: opus sits, codex then sonnet are spares\n\
2539 [roles]\n\
2540 implementers = []\n\
2541 judges = []\n\
2542 reviewers = []\n\
2543 # conductor = \"opus\" # arranges the queue; unset picks a seat like chatter does\n\
2544 # synthesizer = \"opus\" # blends the advisors into one brief; unset picks a seat like chatter does\n\
2545 # synthesizer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\
2546 # language_judge = \"jev\" # kind = \"command\" wrapper deciding if PR text is English; unset keeps the built-in heuristics\n\
2547 # dupes_judge = \"opus\" # judges duplicate-work claims; unset inherits chatter (string or fallback chain)\n\
2548 # fixer = \"opus\" # applies review findings; unset keeps the winner's own author\n\
2549 # fixer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\n\
2550 [graph]\n\
2551 # Gate GitHub prose; secret redaction is always enabled.\n\
2552 github_text_guard = true\n\
2553 # Language of PR / issue titles, bodies and comments; non-English drops the English-only check (commits stay English).\n\
2554 github_language = \"en\"\n\
2555 implementers = 3\n\
2556 judges = 3\n\
2557 deliberate_rounds = 1\n\
2558 reviewers = 3\n\
2559 review_rounds = 6\n\
2560 # Fix rounds a failing verify.gate gets before the run is blocked (0 = none).\n\
2561 gate_fix_rounds = 1\n\
2562 # Rerun a failed required CI check once before a land fix round (flaky tests).\n\
2563 rerun_flaky_checks = true\n\
2564 # Rerun a failed verify.e2e once on the same commit before deciding; a pass is recorded as a flake and filed once as a task.\n\
2565 rerun_failed_e2e = true\n\
2566 # Port the strengths judges named in the losing candidates onto the\n\
2567 # winner before review (best-effort; rolled back on failure or a big diff).\n\
2568 graft_runner_up = true\n\
2569 max_parallel = 4\n\
2570 language = \"en\"\n\
2571 # One CLI conversation per seat: judges keep their own argument\n\
2572 # across deliberation, the fixer keeps its implementation context.\n\
2573 sessions = true\n\
2574 # Reviewer-seat timeout. When timeout_verify is omitted, E2E and\n\
2575 # the final gate inherit this value for compatibility.\n\
2576 timeout_review = 1200\n\
2577 # Optional independent E2E/final-gate timeout; uncomment to keep\n\
2578 # verification independent if timeout_review changes later.\n\
2579 # timeout_verify = 1200\n\
2580 # Longest a seat waits for the shared build cache before it is\n\
2581 # spawned. Never counted against an agent's own timeout; expiry\n\
2582 # holds the run (resumable) instead of failing the agent.\n\
2583 # timeout_resource_wait = 1800\n\n\
2584 # What the chat calls you (persona address and the Chat's turn label).\n\
2585 # [talk]\n\
2586 # standing_authorization = false # machine layer only; bounded chat recovery\n\
2587 # operator_name = \"Commander\"\n\n\
2588 # Chat personas (tone only; the web Chat picks one per conversation).\n\
2589 # Built in: magi, rei, misato, ritsuko, shinji, asuka, kaworu. Entries add to\n\
2590 # them, and one with a built-in's id replaces it. `default` is the plain\n\
2591 # voice and cannot be redefined (it may only set `icon`). Declare this in one\n\
2592 # layer only. `icon` is an optional avatar, display only: an absolute or\n\
2593 # ~/ path to a png/jpg/gif/webp, or a data:image/...;base64 URI, up to\n\
2594 # 256 KiB; a missing or bad one falls back to the built-in avatar.\n\
2595 # [[talk.personas]]\n\
2596 # id = \"gendo\"\n\
2597 # name = \"Gendo Ikari\"\n\
2598 # prompt = \"Speak coldly and tersely, hands folded.\"\n\
2599 # icon = \"~/pictures/gendo.png\"\n\n\
2600 [verify]\n\
2601 # Run once per review round in the winner's worktree; failures are\n\
2602 # fed back to the fixer.\n\
2603 e2e = []\n\
2604 # Final gate. Every command must exit 0 before a merge.\n\
2605 gate = []\n\
2606 # Mechanical fixers (formatters) run in the winner's worktree before\n\
2607 # e2e and before the gate; whatever they change becomes one commit. A\n\
2608 # failing command only warns - the gate stays the arbiter. Same timeout\n\
2609 # as the gate (timeout_verify). Keep it light and idempotent.\n\
2610 # pre_gate = []\n\n\
2611 # Prepare each worktree magi creates (candidates, judges, advisors,\n\
2612 # reviewers, the operator-fix and review-takeover checkouts), in order,\n\
2613 # before any agent or verify command touches it. `copy` reads from the\n\
2614 # primary checkout and never overwrites; `optional` skips a missing\n\
2615 # source. `run` goes through the shell with the worktree as cwd and\n\
2616 # fails the seat on a non-zero exit or timeout (timeout_secs, default\n\
2617 # the verify timeout). Setup must not edit tracked files, and what it\n\
2618 # leaves untracked is kept out of magi's commits. Declare this in one\n\
2619 # layer only.\n\
2620 # [worktree]\n\
2621 # setup = [\n\
2622 # { copy = \".env.example -> .env\" },\n\
2623 # { copy = \".env.local\", optional = true },\n\
2624 # { run = \"pnpm install --frozen-lockfile\", timeout_secs = 900 },\n\
2625 # ]\n\
2626 # pre_clean = [] # Repeatable cleanup before owned clean -fdx.\n\n\
2627 [merge]\n\
2628 # none | local | pr\n\
2629 mode = \"none\"\n\
2630 # expected (default) | none. Set none only in repository config without CI.\n\
2631 # Ignores all check statuses; reviews and approval still apply.\n\
2632 # ci = \"expected\"\n\
2633 # release_bump = true # Rust (Cargo.toml) repositories only; a no-op elsewhere\n\n\
2634 [update]\n\
2635 # off | notify | install — checked in the background, throttled.\n\
2636 mode = \"notify\"\n\
2637 # interval = \"24h\"\n\n\
2638 # Opt-in: magi web updates and restarts automatically when a newer release is found.\n\
2639 # auto_restart = false\n\
2640 # Uses interval above; off / MAGI_NO_AUTOUPDATE disable it.\n\
2641 # Handover drains only short admission transactions; active workers continue\n\
2642 # on their original executable generation while new work uses the new one.\n\
2643 # Standalone magi serve cannot restart.\n\
2644 # Failed tags are skipped until process restart or a different tag.\n\
2645 # Older binaries reject auto_restart: upgrade before adding the key.\n\n\
2646 [daemon]\n\
2647 # Minutes a release-bump pull request (chore/release-v*) may sit with\n\
2648 # no new commit and no check changing state before `magi serve`\n\
2649 # notices and asks you. A failed check is rerun once on its own;\n\
2650 # still red after that escalates at once. 0 turns the watcher off.\n\
2651 # release_stall_minutes = 60\n\n\
2652 [release]\n\
2653 # actions (default) | local. \"local\" is for repositories whose GitHub\n\
2654 # Actions never run (private, no minutes): the release pull request\n\
2655 # does not wait for CI, you approve the merge in magi, and then\n\
2656 # `magi serve` pushes the vX.Y.Z tag (never over an existing one) and\n\
2657 # runs `commands` from a clean checkout of the merge commit. A\n\
2658 # failure holds the release with a notice; it is never retried blind.\n\
2659 # Needs `magi serve` running and [daemon] release_stall_minutes > 0.\n\
2660 # For ordinary pull requests without CI, also set [merge] ci = \"none\".\n\
2661 # mode = \"actions\"\n\
2662 # Run in order; the first failure stops. They see MAGI_RELEASE_VERSION,\n\
2663 # MAGI_RELEASE_TAG, MAGI_RELEASE_COMMIT and MAGI_RELEASE_PR. Make them\n\
2664 # safe to repeat: a crash mid-command is treated as unfinished.\n\
2665 # commands = [\"cargo build --release\", \"gh release create \\\"$MAGI_RELEASE_TAG\\\" --generate-notes\"]\n\
2666 # timeout_minutes = 30\n\
2667 # Repositories whose Cargo.toml is not at the root (e.g. a Tauri app).\n\
2668 # The first entry is the version of record and must be the file the\n\
2669 # repository's auto-tag.yml reads (kind \"cargo\"); the others are\n\
2670 # rewritten to the same version. Paths are relative to the repository\n\
2671 # root. Cargo.lock beside the first entry follows; package-lock.json\n\
2672 # is not touched.\n\
2673 # version_files = [\n\
2674 # { path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n\
2675 # { path = \"package.json\", kind = \"json\" },\n\
2676 # { path = \"src-tauri/tauri.conf.json\", kind = \"json\" },\n\
2677 # ]\n",
2678 );
2679 s
2680 }
2681}
2682
2683pub fn which(program: &str) -> bool {
2685 find_program(program).is_some()
2686}
2687
2688pub fn find_program(program: &str) -> Option<PathBuf> {
2697 find_program_on(program, &std::env::var_os("PATH")?)
2698}
2699
2700pub fn find_program_on(program: &str, paths: &std::ffi::OsStr) -> Option<PathBuf> {
2703 let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".EXE;.CMD;.BAT".into());
2704 find_program_in(program, paths, cfg!(windows).then_some(pathext.as_str()))
2705}
2706
2707fn find_program_in(
2708 program: &str,
2709 paths: &std::ffi::OsStr,
2710 pathext: Option<&str>,
2711) -> Option<PathBuf> {
2712 let p = Path::new(program);
2713 if p.components().count() > 1 {
2714 return p.is_file().then(|| p.to_path_buf());
2715 }
2716 std::env::split_paths(paths).find_map(|dir| match pathext {
2717 Some(exts) => {
2718 let bare = dir.join(program);
2719 if p.extension().is_some() && bare.is_file() {
2720 return Some(bare);
2721 }
2722 exts.split(';')
2723 .filter(|e| !e.is_empty())
2724 .map(|e| dir.join(format!("{program}{}", e.to_lowercase())))
2725 .find(|c| c.is_file())
2726 }
2727 None => Some(dir.join(program)).filter(|c| c.is_file()),
2728 })
2729}
2730
2731const REPO_MARKER: &str = ".magi-repo";
2733
2734fn git_out(repo: &Path, args: &[&str]) -> Option<String> {
2735 use crate::proc::Quiet as _;
2736 #[cfg(test)]
2737 crate::web::request_cost::git();
2738 let out = std::process::Command::new("git")
2739 .args(args)
2740 .quiet()
2741 .current_dir(repo)
2742 .stdin(std::process::Stdio::null())
2743 .output()
2744 .ok()?;
2745 out.status
2746 .success()
2747 .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
2748}
2749
2750fn is_git_worktree(repo: &Path) -> bool {
2753 git_out(repo, &["rev-parse", "--git-dir"]).is_some()
2754}
2755
2756#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2759pub enum OwnerHold {
2760 LandApproval,
2762 HoldContestedMerge,
2764}
2765
2766impl OwnerHold {
2767 pub const ALL: [Self; 2] = [Self::LandApproval, Self::HoldContestedMerge];
2769
2770 pub fn key(self) -> &'static str {
2772 match self {
2773 Self::LandApproval => "land_approval",
2774 Self::HoldContestedMerge => "hold_contested_merge",
2775 }
2776 }
2777
2778 pub fn base_value(self, graph: &Graph) -> bool {
2780 match self {
2781 Self::LandApproval => graph.land_approval,
2782 Self::HoldContestedMerge => graph.hold_contested_merge,
2783 }
2784 }
2785}
2786
2787pub async fn branch_owner_holds(
2790 repo: &Path,
2791 head: &str,
2792) -> (Vec<(OwnerHold, String)>, Vec<String>) {
2793 let mut holds = Vec::new();
2794 let mut diagnostics = Vec::new();
2795 if let Err(error) =
2798 crate::git::git(repo, &["cat-file", "-e", &format!("{head}^{{commit}}")]).await
2799 {
2800 diagnostics.push(format!("cannot read reviewed commit {head}: {error:#}"));
2801 return (holds, diagnostics);
2802 }
2803 for file in ["magi.toml", ".magi/config.toml"] {
2804 let object = format!("{head}:{file}");
2805 let text = match crate::git::git(repo, &["show", &object]).await {
2806 Ok(text) => text,
2807 Err(error) => {
2808 let error = format!("{error:#}");
2810 if !error.contains("does not exist in")
2811 && !error.contains("exists on disk, but not in")
2812 {
2813 diagnostics.push(format!(
2814 "cannot read reviewed branch {file} at {head}: {error}"
2815 ));
2816 }
2817 continue;
2818 }
2819 };
2820 let value = match toml::from_str::<toml::Value>(&text) {
2821 Ok(value) => value,
2822 Err(error) => {
2823 diagnostics.push(format!(
2824 "cannot parse reviewed branch {file} at {head}: {error}"
2825 ));
2826 continue;
2827 }
2828 };
2829 if value.get("include").is_some() || text.contains("{{") || text.contains("{%") {
2830 diagnostics.push(format!("reviewed branch {file} at {head}: only literal owner holds are read; includes and templates are ignored"));
2831 }
2832 for hold in OwnerHold::ALL {
2833 if value
2834 .get("graph")
2835 .and_then(|g| g.get(hold.key()))
2836 .and_then(toml::Value::as_bool)
2837 == Some(true)
2838 {
2839 holds.push((hold, file.to_owned()));
2840 }
2841 }
2842 }
2843 (holds, diagnostics)
2844}
2845
2846#[derive(Deserialize, Default)]
2847struct ProbeMerge {
2848 base: Option<String>,
2849 remote: Option<String>,
2850}
2851
2852#[derive(Deserialize, Default)]
2853struct Probe {
2854 merge: Option<ProbeMerge>,
2855}
2856
2857fn probe_merge(path: &Path, repo: &Path) -> Option<ProbeMerge> {
2863 if !path.is_file() {
2864 return None;
2865 }
2866 let paths = [path.to_path_buf()];
2867 let mut engine = teravars::Engine::default();
2868 let mut ctx = Config::render_ctx(&paths);
2869 ctx.insert("repo", &repo.to_string_lossy());
2872 ctx.insert(
2873 "repo_name",
2874 &repo.file_name().unwrap_or_default().to_string_lossy(),
2875 );
2876 if let Ok(merged) = teravars::load_merged(&paths, &mut engine, &ctx)
2877 && let Ok(probe) = toml::Value::Table(merged.config).try_into::<Probe>()
2878 {
2879 return probe.merge;
2880 }
2881 let text = std::fs::read_to_string(path).ok()?;
2882 toml::from_str::<Probe>(&text).ok()?.merge
2883}
2884
2885fn probe_remote_base(repo: &Path) -> (String, Option<String>) {
2887 let mut remote = None;
2888 let mut base = None;
2889 let mut sources: Vec<PathBuf> = Config::machine_layer().into_iter().collect();
2890 sources.push(repo.join("magi.toml"));
2891 sources.push(repo.join(".magi").join("config.toml"));
2892 for path in sources {
2893 if let Some(m) = probe_merge(&path, repo) {
2894 remote = remote.or(m.remote.filter(|s| !s.trim().is_empty()));
2895 base = base.or(m.base.filter(|s| !s.trim().is_empty()));
2896 }
2897 }
2898 (remote.unwrap_or_else(|| "origin".to_owned()), base)
2899}
2900
2901fn resolve_remote_base(repo: &Path) -> Result<(String, String)> {
2903 let (remote, base) = probe_remote_base(repo);
2904 let base = match base {
2905 Some(b) => b,
2906 None => {
2907 let head = format!("refs/remotes/{remote}/HEAD");
2908 git_out(repo, &["symbolic-ref", "--quiet", &head])
2909 .and_then(|s| crate::git::remote_head_branch(&remote, &s))
2910 .with_context(|| {
2911 format!(
2912 "cannot tell which branch of `{remote}` holds magi.toml: \
2913 set [merge] base, or run `git remote set-head {remote} -a`"
2914 )
2915 })?
2916 }
2917 };
2918 Ok((remote, base))
2919}
2920
2921fn fnv_hex(text: &str) -> String {
2922 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
2923 for b in text.bytes() {
2924 hash ^= u64::from(b);
2925 hash = hash.wrapping_mul(0x0100_0000_01b3);
2926 }
2927 format!("{hash:016x}")
2928}
2929
2930fn declares_include(text: &str) -> bool {
2936 match toml::from_str::<toml::Table>(text) {
2937 Ok(table) => {
2938 table.contains_key("include")
2939 || table
2940 .get("teravars")
2941 .and_then(toml::Value::as_table)
2942 .is_some_and(|t| t.contains_key("include"))
2943 }
2944 Err(_) => text.contains("include"),
2945 }
2946}
2947
2948fn extract_tree(repo: &Path, sha: &str, dest: &Path) -> Result<()> {
2951 use crate::proc::Quiet as _;
2952 #[cfg(test)]
2953 crate::web::request_cost::git();
2954 let mut archive = std::process::Command::new("git")
2955 .args(["archive", "--format=tar", sha])
2956 .quiet()
2957 .current_dir(repo)
2958 .stdin(std::process::Stdio::null())
2959 .stdout(std::process::Stdio::piped())
2960 .stderr(std::process::Stdio::null())
2961 .spawn()
2962 .context("running git archive")?;
2963 let tar = std::process::Command::new("tar")
2964 .arg("-x")
2965 .arg("-C")
2966 .arg(dest)
2967 .quiet()
2968 .stdin(archive.stdout.take().context("git archive has no stdout")?)
2969 .output()
2970 .context("running tar")?;
2971 let status = archive.wait().context("waiting for git archive")?;
2972 if !status.success() || !tar.status.success() {
2973 bail!(
2974 "cannot unpack {sha} for the config's includes: {}",
2975 String::from_utf8_lossy(&tar.stderr).trim()
2976 );
2977 }
2978 Ok(())
2979}
2980
2981fn remote_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2984 let (remote, base) = resolve_remote_base(repo)?;
2985 let tracking = format!("refs/remotes/{remote}/{base}");
2986 let spec = format!("{tracking}^{{commit}}");
2987 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
2988 .map(|s| s.trim().to_owned())
2989 .filter(|s| !s.is_empty())
2990 .with_context(|| {
2991 format!(
2992 "`{remote}/{base}` does not exist in this checkout; fetch it \
2993 (`git fetch {remote} {base}`) or set [merge] base/remote. magi will not read \
2994 a possibly stale local magi.toml instead"
2995 )
2996 })?;
2997 let key = format!("{sha}-{}", fnv_hex(&repo.to_string_lossy()));
2998 let rels = [".magi/config.toml", "magi.toml"];
2999 let mut texts: Vec<(&str, String)> = Vec::new();
3000 for rel in rels {
3001 let object = format!("{sha}:{rel}");
3002 if git_out(repo, &["cat-file", "-e", &object]).is_none() {
3003 continue;
3004 }
3005 let Some(text) = git_out(repo, &["show", &object]) else {
3006 bail!("cannot read {rel} from {remote}/{base} ({sha})");
3007 };
3008 texts.push((rel, text));
3009 }
3010 let wants_tree = texts.iter().any(|(_, t)| declares_include(t));
3011 let build = |root: &Path| -> Result<PathBuf> {
3015 let final_dir = root.join(&key);
3016 if !final_dir.is_dir() {
3017 std::fs::create_dir_all(root)?;
3018 let tmp = root.join(format!(
3019 "{key}.tmp-{}-{}",
3020 std::process::id(),
3021 std::time::SystemTime::now()
3022 .duration_since(std::time::UNIX_EPOCH)
3023 .map(|d| d.as_nanos())
3024 .unwrap_or_default()
3025 ));
3026 let filled = (|| -> Result<()> {
3027 std::fs::create_dir_all(&tmp)?;
3028 if wants_tree {
3029 extract_tree(repo, &sha, &tmp)?;
3030 }
3031 for (rel, text) in &texts {
3032 let file = tmp.join(rel);
3033 let parent = file.parent().unwrap_or(&tmp);
3034 std::fs::create_dir_all(parent)?;
3035 std::fs::write(&file, text)?;
3036 std::fs::write(parent.join(REPO_MARKER), repo.to_string_lossy().as_bytes())?;
3037 }
3038 Ok(())
3039 })();
3040 if let Err(e) = filled {
3041 let _ = std::fs::remove_dir_all(&tmp);
3042 return Err(e);
3043 }
3044 if std::fs::rename(&tmp, &final_dir).is_err() {
3045 let _ = std::fs::remove_dir_all(&tmp);
3047 if !final_dir.is_dir() {
3048 bail!("cannot place {}", final_dir.display());
3049 }
3050 }
3051 }
3052 Ok(final_dir)
3053 };
3054 let common = git_out(
3055 repo,
3056 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
3057 )
3058 .map(|s| PathBuf::from(s.trim()).join("magi").join("config"));
3059 let dir = match common.map(|c| build(&c)) {
3060 Some(Ok(d)) => d,
3061 _ => build(&std::env::temp_dir().join("magi-config"))
3062 .with_context(|| format!("extracting config from {remote}/{base}"))?,
3063 };
3064 Ok(texts.iter().map(|(rel, _)| dir.join(rel)).collect())
3065}
3066
3067#[cfg(test)]
3068mod tests {
3069 #[test]
3070 fn standing_authorization_is_only_from_the_named_machine_layer() {
3071 let dir = tempfile::tempdir().unwrap();
3072 let machine = dir.path().join("machine.toml");
3073 let repo = dir.path().join("magi.toml");
3074 std::fs::write(&machine, "[talk]\nstanding_authorization = false\n").unwrap();
3075 std::fs::write(&repo, "[talk]\nstanding_authorization = true\n").unwrap();
3076 let layers = [machine.clone(), repo.clone()];
3077 let load = |paths| Config::load_layers_with_machine(paths, Some(machine.clone())).unwrap();
3078 assert!(!load(&layers).talk.standing_authorization);
3079 assert!(
3080 !load(std::slice::from_ref(&repo))
3081 .talk
3082 .standing_authorization
3083 );
3084 std::fs::write(&machine, "[talk]\nstanding_authorization = true\n").unwrap();
3085 std::fs::write(&repo, "[talk]\nstanding_authorization = false\n").unwrap();
3086 assert!(load(&layers).talk.standing_authorization);
3087 }
3088
3089 #[test]
3090 fn run_records_with_the_retired_editing_network_key_still_load() {
3091 for value in ["enabled", "restricted"] {
3093 let mut graph = serde_json::to_value(Graph::default()).unwrap();
3094 graph["editing_network"] = serde_json::json!(value);
3095 let back: Graph = serde_json::from_value(graph).unwrap();
3096 assert!(
3097 serde_json::to_value(&back)
3098 .unwrap()
3099 .get("editing_network")
3100 .is_none()
3101 );
3102 let from_toml: Graph = toml::from_str(&format!("editing_network = {value:?}")).unwrap();
3103 assert!(
3104 !toml::to_string(&from_toml)
3105 .unwrap()
3106 .contains("editing_network")
3107 );
3108 }
3109 }
3110
3111 #[test]
3112 fn coordination_defaults_off_and_validates_rendered_layer_values() {
3113 let dir = tempfile::tempdir().unwrap();
3114 let machine = dir.path().join("machine.toml");
3115 let repo = dir.path().join("repo.toml");
3116 std::fs::write(&machine, "").unwrap();
3117 assert!(Config::default().coordination.is_none());
3118 assert!(Config::load(&machine).unwrap().coordination.is_none());
3119 std::fs::write(
3120 &machine,
3121 r#"
3122[vars]
3123contract = "updater.contract"
3124[coordination]
3125contract_file = "{{ vars.contract }}"
3126contract_token = "protocol-v1"
3127lock_file = "updater.lock"
3128"#,
3129 )
3130 .unwrap();
3131 let cfg = Config::load(&machine).unwrap();
3132 let policy = cfg.coordination.unwrap();
3133 assert_eq!(policy.contract_file, "updater.contract");
3134 assert_eq!(policy.contract_token, "protocol-v1");
3135 assert_eq!(policy.lock_file, "updater.lock");
3136 std::fs::write(&repo, "[coordination]\nlock_file = 'repository.lock'\n").unwrap();
3137 let cfg = Config::load_layers(&[machine.clone(), repo.clone()]).unwrap();
3138 let policy = cfg.coordination.unwrap();
3139 assert_eq!(policy.contract_file, "updater.contract");
3140 assert_eq!(policy.lock_file, "repository.lock");
3141 std::fs::write(
3142 &repo,
3143 r#"
3144[vars]
3145bad = "../escape"
3146[coordination]
3147lock_file = "{{ vars.bad }}"
3148"#,
3149 )
3150 .unwrap();
3151 let error = Config::load_layers(&[machine, repo]).unwrap_err();
3152 assert!(format!("{error:#}").contains("coordination.lock_file"));
3153 }
3154
3155 #[test]
3156 fn coordination_rejects_invalid_names_tokens_and_incomplete_sections() {
3157 let dir = tempfile::tempdir().unwrap();
3158 let path = dir.path().join("config.toml");
3159 let valid = toml::toml! {
3160 [coordination]
3161 contract_file = "updater.contract"
3162 contract_token = "protocol-v1"
3163 lock_file = "updater.lock"
3164 };
3165 for key in ["contract_file", "lock_file"] {
3166 for bad in [
3167 "",
3168 " ",
3169 " file",
3170 "file ",
3171 "\tfile",
3172 "file\t",
3173 ".",
3174 "..",
3175 "file..name",
3176 "../escape",
3177 "a/b",
3178 "a\\b",
3179 "/absolute",
3180 "C:drive",
3181 "C:\\absolute",
3182 "nul\0name",
3183 ] {
3184 let mut table = valid.clone();
3185 table["coordination"][key] = bad.into();
3186 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3187 let error = Config::load(&path).unwrap_err();
3188 assert!(
3189 format!("{error:#}").contains(&format!("coordination.{key}")),
3190 "{bad:?}: {error:#}"
3191 );
3192 }
3193 }
3194 for bad in ["", " ", " token", "token ", "two\nlines", "two\rlines"] {
3195 let mut table = valid.clone();
3196 table["coordination"]["contract_token"] = bad.into();
3197 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3198 let error = Config::load(&path).unwrap_err();
3199 assert!(
3200 format!("{error:#}").contains("coordination.contract_token"),
3201 "{error:#}"
3202 );
3203 }
3204 for key in ["contract_file", "contract_token", "lock_file"] {
3205 let mut table = valid.clone();
3206 table["coordination"].as_table_mut().unwrap().remove(key);
3207 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3208 let error = Config::load(&path).unwrap_err();
3209 assert!(
3210 format!("{error:#}").contains(&format!("coordination.{key}")),
3211 "{error:#}"
3212 );
3213 }
3214 let mut table = valid;
3215 table["coordination"]
3216 .as_table_mut()
3217 .unwrap()
3218 .insert("typo".into(), "value".into());
3219 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
3220 assert!(format!("{:#}", Config::load(&path).unwrap_err()).contains("typo"));
3221 }
3222
3223 #[test]
3224 fn context_window_prefers_exact_then_longest_prefix_and_user_over_builtin() {
3225 let mut cfg = Config::default();
3226 assert_eq!(
3227 cfg.context_window("claude-sonnet-4-5-20250929"),
3228 Some(200_000)
3229 );
3230 assert_eq!(cfg.context_window("gpt-4.1-mini"), Some(1_000_000));
3231 assert_eq!(cfg.context_window("mystery-model"), None);
3232 cfg.context_windows
3233 .insert("claude-sonnet-4-5".into(), 1_000_000);
3234 cfg.context_windows.insert("claude-sonnet-4".into(), 5);
3235 cfg.context_windows.insert("mystery".into(), 32_768);
3236 assert_eq!(
3238 cfg.context_window("claude-sonnet-4-5-20250929"),
3239 Some(1_000_000)
3240 );
3241 cfg.context_windows
3243 .insert("claude-sonnet-4-5-20250929".into(), 7);
3244 assert_eq!(cfg.context_window("claude-sonnet-4-5-20250929"), Some(7));
3245 assert_eq!(cfg.context_window("mystery-model"), Some(32_768));
3246 }
3247
3248 use super::*;
3249
3250 #[test]
3253 fn windows_lookup_picks_the_cmd_shim_over_the_extensionless_script() {
3254 let dir = tempfile::tempdir().unwrap();
3255 std::fs::write(dir.path().join("codex"), "#!/bin/sh\n").unwrap();
3256 std::fs::write(dir.path().join("codex.cmd"), "@echo off\n").unwrap();
3257 let paths = dir.path().as_os_str();
3258 assert_eq!(
3259 find_program_in("codex", paths, Some(".EXE;.CMD")),
3260 Some(dir.path().join("codex.cmd"))
3261 );
3262 assert_eq!(
3263 find_program_in("codex", paths, None),
3264 Some(dir.path().join("codex"))
3265 );
3266 assert_eq!(find_program_in("claude", paths, Some(".EXE;.CMD")), None);
3267 }
3268
3269 fn spec(id: &str) -> AgentSpec {
3270 AgentSpec {
3271 id: id.to_owned(),
3272 kind: AgentKind::Command,
3273 model: None,
3274 command: vec!["true".to_owned()],
3275 extra_args: Vec::new(),
3276 env: BTreeMap::new(),
3277 prompt_delivery: None,
3278 max_turn_secs: None,
3279 }
3280 }
3281
3282 #[test]
3283 fn merge_ci_defaults_expected_and_requires_an_explicit_valid_opt_out() {
3284 let default: Merge = toml::from_str("").unwrap();
3285 assert_eq!(default.ci, MergeCi::Expected);
3286 let config = layered("", "[merge]\nci = \"none\"\n").unwrap();
3287 assert_eq!(
3288 config.merge.ci.expectation(),
3289 crate::land::CiExpectation::Absent
3290 );
3291 assert!(toml::from_str::<Merge>("ci = \"typo\"").is_err());
3292 assert!(Config::starter_toml().contains("# ci = \"expected\""));
3293 }
3294
3295 #[test]
3296 fn github_text_guard_defaults_on_and_can_be_disabled() {
3297 let default: Graph = toml::from_str("").unwrap();
3298 assert!(default.github_text_guard);
3299 let disabled: Graph = toml::from_str("github_text_guard = false").unwrap();
3300 assert!(!disabled.github_text_guard);
3301 let config = layered("", "[graph]\ngithub_text_guard = false\n").unwrap();
3302 assert!(!config.graph.github_text_guard);
3303 assert!(Config::starter_toml().contains("github_text_guard = true"));
3304 }
3305
3306 #[test]
3307 fn rerun_flaky_checks_defaults_on_and_is_in_the_starter() {
3308 assert!(Graph::default().rerun_flaky_checks);
3309 let off: Graph = toml::from_str("rerun_flaky_checks = false").unwrap();
3310 assert!(!off.rerun_flaky_checks);
3311 assert!(Config::starter_toml().contains("rerun_flaky_checks = true"));
3312 }
3313
3314 #[test]
3315 fn timeout_verify_omitted_from_old_toml_inherits_timeout_review() {
3316 let g: Graph = toml::from_str("timeout_review = 3600").expect("parse");
3321 assert_eq!(g.timeout_verify, None);
3322 assert_eq!(g.verify_timeout(), 3600);
3323 }
3324
3325 #[test]
3326 fn shrinking_timeout_review_does_not_shrink_timeout_verify() {
3327 let g: Graph = toml::from_str("timeout_review = 45").expect("parse");
3332 assert_eq!(g.timeout_review, 45);
3333 assert_eq!(
3334 g.verify_timeout(),
3335 45,
3336 "an omitted legacy value follows review"
3337 );
3338 let explicit: Graph = toml::from_str("timeout_review = 45\ntimeout_verify = 1200")
3339 .expect("parse explicit override");
3340 assert_eq!(explicit.verify_timeout(), 1200);
3341 }
3342
3343 #[test]
3344 fn graph_implementers_new_key_loads_and_old_key_is_an_alias() {
3345 let g: Graph = toml::from_str("implementers = 4\n").unwrap();
3346 assert_eq!(g.implementers, 4);
3347 let g: Graph = toml::from_str("candidates = 5\n").unwrap();
3348 assert_eq!(g.implementers, 5);
3349 }
3350
3351 fn layered(lower: &str, upper: &str) -> Result<Config> {
3352 let dir = tempfile::tempdir().unwrap();
3353 let a = dir.path().join("a.toml");
3354 let b = dir.path().join("b.toml");
3355 std::fs::write(&a, lower).unwrap();
3356 std::fs::write(&b, upper).unwrap();
3357 Config::load_layers(&[a, b])
3358 }
3359
3360 #[test]
3361 fn graph_implementers_higher_layer_wins_across_spellings() {
3362 let c = layered("[graph]\ncandidates = 2\n", "[graph]\nimplementers = 5\n").unwrap();
3363 assert_eq!(c.graph.implementers, 5);
3364 let c = layered("[graph]\nimplementers = 2\n", "[graph]\ncandidates = 5\n").unwrap();
3365 assert_eq!(c.graph.implementers, 5);
3366 let c = layered("[graph]\ncandidates = 2\n", "[graph]\njudges = 3\n").unwrap();
3367 assert_eq!(c.graph.implementers, 2);
3368 }
3369
3370 #[test]
3371 fn graph_implementers_both_keys_in_one_layer_is_refused() {
3372 let err = layered("", "[graph]\ncandidates = 2\nimplementers = 3\n")
3373 .unwrap_err()
3374 .to_string();
3375 assert!(
3376 err.contains("candidates") && err.contains("implementers"),
3377 "{err}"
3378 );
3379 assert!(err.contains("b.toml"), "{err}");
3380 }
3381
3382 #[test]
3383 fn a_toml_layer_written_before_these_fields_existed_still_parses() {
3384 let g: Graph =
3388 toml::from_str("candidates = 1\nreviewers = 3\nreview_rounds = 6\nmax_parallel = 4\n")
3389 .expect("an old-shaped [graph] table must still parse");
3390 assert_eq!(g.verify_timeout(), Graph::default().timeout_review);
3391 assert!(
3392 !g.e2e_every_round,
3393 "off by default, same as before this field existed"
3394 );
3395 }
3396
3397 #[test]
3398 fn empty_roles_rotate_judges_off_their_own_candidate() {
3399 let cfg = Config {
3402 agents: vec![spec("a"), spec("b"), spec("c")],
3403 graph: Graph {
3404 implementers: 3,
3405 ..Graph::default()
3406 },
3407 ..Config::default()
3408 };
3409 let roles = cfg.resolve_roles().unwrap();
3410 let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
3411 let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
3412 assert_eq!(impls, ["a", "b", "c"]);
3413 assert_eq!(judges, ["b", "c", "a"]);
3414 for (i, j) in judges.iter().enumerate() {
3415 assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
3416 }
3417 }
3418
3419 #[test]
3420 fn single_agent_roster_fills_every_seat() {
3421 let cfg = Config {
3422 agents: vec![spec("solo")],
3423 graph: Graph {
3424 implementers: 3,
3425 ..Graph::default()
3426 },
3427 ..Config::default()
3428 };
3429 let roles = cfg.resolve_roles().unwrap();
3430 assert_eq!(roles.implementers.len(), 3);
3431 assert!(roles.judges.iter().all(|a| a.id == "solo"));
3432 }
3433
3434 #[test]
3435 fn implementer_roster_is_the_whole_agent_list_untruncated_when_unset() {
3436 let cfg = Config {
3441 agents: vec![spec("a"), spec("b"), spec("c")],
3442 graph: Graph {
3443 implementers: 1,
3444 ..Graph::default()
3445 },
3446 ..Config::default()
3447 };
3448 let roles = cfg.resolve_roles().unwrap();
3449 assert_eq!(roles.implementers.len(), 1);
3450 let roster: Vec<&str> = roles
3451 .implementer_roster
3452 .iter()
3453 .map(|a| a.id.as_str())
3454 .collect();
3455 assert_eq!(roster, ["a", "b", "c"]);
3456 }
3457
3458 #[test]
3459 fn implementer_roster_follows_explicit_ids_in_the_order_named() {
3460 let cfg = Config {
3461 agents: vec![spec("a"), spec("b"), spec("c")],
3462 roles: Roles {
3463 implementers: vec!["c".to_owned(), "a".to_owned()],
3464 ..Roles::default()
3465 },
3466 graph: Graph {
3467 implementers: 1,
3468 ..Graph::default()
3469 },
3470 ..Config::default()
3471 };
3472 let roles = cfg.resolve_roles().unwrap();
3473 assert_eq!(roles.implementers.len(), 1);
3475 assert_eq!(roles.implementers[0].id, "c");
3476 let roster: Vec<&str> = roles
3477 .implementer_roster
3478 .iter()
3479 .map(|a| a.id.as_str())
3480 .collect();
3481 assert_eq!(roster, ["c", "a"]);
3482 }
3483
3484 #[test]
3485 fn explicit_roles_win() {
3486 let cfg = Config {
3487 agents: vec![spec("a"), spec("b")],
3488 roles: Roles {
3489 implementers: vec!["b".to_owned()],
3490 judges: vec!["a".to_owned()],
3491 reviewers: Vec::new(),
3492 fixer: Some("a".into()),
3493 ..Roles::default()
3494 },
3495 ..Config::default()
3496 };
3497 let roles = cfg.resolve_roles().unwrap();
3498 assert!(roles.implementers.iter().all(|a| a.id == "b"));
3499 assert!(roles.judges.iter().all(|a| a.id == "a"));
3500 let fixer = roles.fixer.unwrap();
3501 assert_eq!(fixer.len(), 1);
3502 assert_eq!(fixer[0].id, "a");
3503 assert_eq!(roles.conductor.id, "a");
3504 }
3505
3506 #[test]
3507 fn fixer_takes_a_string_or_an_ordered_chain() {
3508 let one: Roles = toml::from_str("fixer = \"a\"").unwrap();
3509 assert_eq!(one.fixer.as_ref().unwrap().ids(), ["a"]);
3510 let chain: Roles = toml::from_str("fixer = [\"b\", \"a\"]").unwrap();
3511 assert_eq!(chain.fixer.as_ref().unwrap().ids(), ["b", "a"]);
3512
3513 let resolve = |fixer: Option<AgentChoice>| {
3514 Config {
3515 agents: vec![spec("a"), spec("b"), spec("c")],
3516 roles: Roles {
3517 fixer,
3518 ..Roles::default()
3519 },
3520 ..Config::default()
3521 }
3522 .resolve_roles()
3523 };
3524 let ids = |r: &ResolvedRoles| -> Vec<String> {
3525 r.fixer
3526 .as_ref()
3527 .unwrap()
3528 .iter()
3529 .map(|s| s.id.clone())
3530 .collect()
3531 };
3532 assert_eq!(ids(&resolve(Some("c".into())).unwrap()), ["c"]);
3534 assert!(resolve(None).unwrap().fixer.is_none());
3535 let chain = AgentChoice::Chain(vec!["b".into(), "zzz".into(), "a".into(), "b".into()]);
3537 assert_eq!(ids(&resolve(Some(chain)).unwrap()), ["b", "a"]);
3538 let err = resolve(Some(AgentChoice::Chain(vec!["zzz".into()]))).unwrap_err();
3540 assert!(format!("{err:#}").contains("fixer"), "{err:#}");
3541 }
3542
3543 #[test]
3544 fn unknown_agent_id_is_an_error() {
3545 let cfg = Config {
3546 agents: vec![spec("a")],
3547 roles: Roles {
3548 judges: vec!["nope".to_owned()],
3549 ..Roles::default()
3550 },
3551 ..Config::default()
3552 };
3553 assert!(cfg.resolve_roles().is_err());
3554 }
3555
3556 #[test]
3557 fn conductor_role_is_resolved_validated_and_has_a_fallback() {
3558 let mut cfg = Config {
3559 agents: vec![spec("a"), spec("b")],
3560 ..Config::default()
3561 };
3562 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "a");
3563
3564 cfg.roles.conductor = Some("b".into());
3565 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "b");
3566
3567 cfg.roles.conductor = Some("missing".into());
3568 assert!(cfg.resolve_roles().is_err());
3569 }
3570
3571 #[test]
3572 fn a_standalone_role_takes_a_string_or_an_array_and_round_trips() {
3573 let one: Roles = toml::from_str("synthesizer = \"opus\"").unwrap();
3574 assert_eq!(one.synthesizer, Some(AgentChoice::One("opus".to_owned())));
3575 assert_eq!(primary(one.synthesizer.as_ref()), Some("opus"));
3576
3577 let chain: Roles = toml::from_str("chatter = [\"opus\", \"codex\"]").unwrap();
3578 assert_eq!(chain.chatter.as_ref().unwrap().ids(), ["opus", "codex"]);
3579 assert_eq!(primary(chain.chatter.as_ref()), Some("opus"));
3580
3581 for roles in [one, chain] {
3582 let text = toml::to_string(&roles).unwrap();
3583 let back: Roles = toml::from_str(&text).unwrap();
3584 assert_eq!(back.synthesizer, roles.synthesizer);
3585 assert_eq!(back.chatter, roles.chatter);
3586 }
3587 let text = toml::to_string(&Roles {
3588 conductor: Some("x".into()),
3589 ..Roles::default()
3590 })
3591 .unwrap();
3592 assert!(
3593 text.contains("conductor = \"x\""),
3594 "string stays a string: {text}"
3595 );
3596 assert!(toml::from_str::<Roles>("synthesizer = 3").is_err());
3597 }
3598
3599 #[test]
3600 fn dupes_judge_role_accepts_strings_and_chains_and_round_trips() {
3601 for (text, ids) in [
3602 (r#"dupes_judge = "dedicated""#, vec!["dedicated"]),
3603 (
3604 r#"dupes_judge = ["first", "second"]"#,
3605 vec!["first", "second"],
3606 ),
3607 ("dupes_judge = []", vec![]),
3608 ] {
3609 let roles: Roles = toml::from_str(text).unwrap();
3610 assert_eq!(roles.dupes_judge.as_ref().unwrap().ids(), ids);
3611 let serialized = toml::to_string(&roles).unwrap();
3612 let back: Roles = toml::from_str(&serialized).unwrap();
3613 assert_eq!(back.dupes_judge, roles.dupes_judge);
3614 assert!(serialized.contains(text));
3615 }
3616 assert!(toml::from_str::<Roles>("dupes_judge = 3").is_err());
3617 assert!(Roles::default().dupes_judge.is_none());
3618 assert!(Config::starter_toml().contains("# dupes_judge ="));
3619
3620 let mut cfg = Config {
3622 agents: vec![spec("a")],
3623 ..Config::default()
3624 };
3625 cfg.roles.dupes_judge = Some("missing".into());
3626 assert!(cfg.resolve_roles().is_ok());
3627 }
3628
3629 #[test]
3630 fn an_empty_choice_counts_as_unset() {
3631 assert!(AgentChoice::Chain(Vec::new()).ids().is_empty());
3632 assert!(AgentChoice::One(" ".to_owned()).ids().is_empty());
3633 assert_eq!(primary(Some(&AgentChoice::Chain(vec![]))), None);
3634 }
3635
3636 #[test]
3637 fn synthesizer_role_is_a_lazy_lookup_with_the_same_fallback_as_chatter() {
3638 let mut cfg = Config {
3644 agents: vec![spec("a"), spec("b")],
3645 ..Config::default()
3646 };
3647 let want = primary(cfg.roles.synthesizer.as_ref());
3648 assert_eq!(
3649 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
3650 .unwrap()
3651 .id,
3652 "a",
3653 "unset falls back to agent::pick's own default order"
3654 );
3655
3656 cfg.roles.synthesizer = Some("b".into());
3657 let want = primary(cfg.roles.synthesizer.as_ref());
3658 assert_eq!(
3659 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
3660 .unwrap()
3661 .id,
3662 "b",
3663 "the named agent wins over the default order"
3664 );
3665 }
3666
3667 #[test]
3668 fn empty_roster_is_an_error() {
3669 assert!(Config::default().resolve_roles().is_err());
3670 }
3671
3672 #[test]
3673 fn advise_defaults_to_on_with_three_proposals() {
3674 let g = Graph::default();
3675 assert!(g.advise);
3676 assert!(g.graft_runner_up, "graft is on by default");
3677 assert_eq!(g.advisors, 3);
3678 }
3679
3680 #[test]
3681 fn unset_advisors_falls_back_to_the_judge_roster() {
3682 let cfg = Config {
3683 agents: vec![spec("a"), spec("b")],
3684 roles: Roles {
3685 judges: vec!["b".to_owned()],
3686 ..Roles::default()
3687 },
3688 graph: Graph {
3689 advisors: 2,
3690 ..Graph::default()
3691 },
3692 ..Config::default()
3693 };
3694 let advisors = cfg.advisors().expect("advisors resolve");
3695 assert_eq!(advisors.len(), 2);
3696 assert!(
3697 advisors.iter().all(|a| a.id == "b"),
3698 "an unset [roles] advisors must fall back to [roles] judges: {advisors:?}"
3699 );
3700 }
3701
3702 #[test]
3703 fn an_explicit_advisor_roster_wins_over_the_judge_fallback() {
3704 let cfg = Config {
3705 agents: vec![spec("a"), spec("b")],
3706 roles: Roles {
3707 judges: vec!["b".to_owned()],
3708 advisors: vec!["a".to_owned()],
3709 ..Roles::default()
3710 },
3711 graph: Graph {
3712 advisors: 2,
3713 ..Graph::default()
3714 },
3715 ..Config::default()
3716 };
3717 let advisors = cfg.advisors().expect("advisors resolve");
3718 assert!(advisors.iter().all(|a| a.id == "a"));
3719 }
3720
3721 #[test]
3727 fn an_unconfigured_advisor_and_judge_roster_resolve_to_the_same_agents() {
3728 let cfg = Config {
3729 agents: vec![spec("a"), spec("b"), spec("c")],
3730 graph: Graph {
3731 advisors: 3,
3732 judges: 3,
3733 ..Graph::default()
3734 },
3735 ..Config::default()
3736 };
3737 let advisors = cfg.advisors().expect("advisors resolve");
3738 let judges = cfg.resolve_roles().expect("roles resolve").judges;
3739 let advisor_ids: Vec<&str> = advisors.iter().map(|a| a.id.as_str()).collect();
3740 let judge_ids: Vec<&str> = judges.iter().map(|a| a.id.as_str()).collect();
3741 assert_eq!(
3742 advisor_ids, judge_ids,
3743 "an unconfigured advisor roster must be the same seats an unconfigured judge panel gets"
3744 );
3745 }
3746
3747 #[test]
3748 fn an_unresolvable_advisor_seat_is_an_error_naming_the_id() {
3749 let cfg = Config {
3750 agents: vec![spec("a")],
3751 roles: Roles {
3752 advisors: vec!["nope".to_owned()],
3753 ..Roles::default()
3754 },
3755 graph: Graph {
3756 advisors: 1,
3757 ..Graph::default()
3758 },
3759 ..Config::default()
3760 };
3761 let err = cfg.advisors().expect_err("`nope` is not in the roster");
3762 assert!(format!("{err:#}").contains("nope"));
3763 }
3764
3765 #[test]
3766 fn repos_default_to_no_roots_and_a_day_of_trust() {
3767 assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
3768 assert_eq!(Config::default().repos.scan_ttl, 86_400);
3769 assert_eq!(Config::default().repos.fetch_interval, 600);
3770 assert!(!Config::default().repos.auto_clone);
3771 assert!(Config::default().repos.clone_command.is_none());
3772 }
3773
3774 #[test]
3775 fn a_config_file_with_no_repos_table_still_loads() {
3776 let dir = tempfile::tempdir().unwrap();
3777 let path = dir.path().join("magi.toml");
3778 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
3779 let cfg = Config::load(&path).expect("must load without [repos]");
3780 assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
3781 assert_eq!(cfg.repos.scan_ttl, 86_400);
3782 }
3783
3784 #[test]
3799 fn a_test_build_does_not_read_the_operators_machine_config() {
3800 let repo = tempfile::tempdir().unwrap();
3801 std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
3802
3803 let layers = Config::layers(repo.path());
3804 assert_eq!(
3805 layers,
3806 vec![repo.path().join("magi.toml")],
3807 "only the fixture's own file may be a layer"
3808 );
3809 if let Some(real) = dirs::config_dir() {
3810 let machine = real.join("magi").join("config.toml");
3811 assert!(
3812 !layers.contains(&machine),
3813 "the operator's {} must not be a layer in a test build",
3814 machine.display()
3815 );
3816 }
3817 }
3818
3819 #[test]
3820 fn auto_upgrade_config_defaults_and_opt_in() {
3821 let default: Update = toml::from_str("").unwrap();
3822 assert!(!default.auto_restart);
3823 assert_eq!(default.mode, UpdateMode::Notify);
3824 let enabled: Update = toml::from_str("auto_restart = true\ninterval = \"2h\"\n").unwrap();
3825 assert!(enabled.auto_restart);
3826 assert_eq!(enabled.interval.as_deref(), Some("2h"));
3827 assert!(toml::from_str::<Update>("auto_restart = \"yes\"").is_err());
3828 }
3829
3830 #[test]
3831 fn starter_toml_loads_through_teravars() {
3832 let dir = tempfile::tempdir().unwrap();
3833 let path = dir.path().join("magi.toml");
3834 std::fs::write(&path, Config::starter_toml()).unwrap();
3835 let parsed = Config::load(&path).expect("starter config must load");
3836 assert_eq!(parsed.graph.implementers, 3);
3837 assert_eq!(parsed.merge.mode, MergeMode::None);
3838 assert_eq!(parsed.merge.style, MergeStyle::Merge);
3839 assert!(parsed.graph.sessions);
3840 assert!(parsed.graph.github_text_guard);
3841 assert_eq!(parsed.graph.timeout_review, 1200);
3842 assert_eq!(parsed.graph.verify_timeout(), 1200);
3843 assert_eq!(parsed.update.mode, UpdateMode::Notify);
3844 }
3845
3846 #[test]
3847 fn release_defaults_to_actions_and_the_starter_documents_it() {
3848 let dir = tempfile::tempdir().unwrap();
3849 let path = dir.path().join("magi.toml");
3850 std::fs::write(&path, Config::starter_toml()).unwrap();
3851 let r = Config::load(&path).unwrap().release;
3852 assert_eq!(r.mode, ReleaseMode::Actions);
3853 assert!(!r.is_local());
3854 assert!(r.commands.is_empty());
3855 assert_eq!(r.timeout_minutes, 30);
3856 assert!(Config::starter_toml().contains("# mode = \"actions\""));
3857 }
3858
3859 #[test]
3860 fn release_local_parses_and_unknown_keys_are_refused() {
3861 let dir = tempfile::tempdir().unwrap();
3862 let path = dir.path().join("magi.toml");
3863 std::fs::write(
3864 &path,
3865 "[release]\nmode = \"local\"\ncommands = [\"true\", \"echo $MAGI_RELEASE_TAG\"]\ntimeout_minutes = 5\n",
3866 )
3867 .unwrap();
3868 let r = Config::load(&path).unwrap().release;
3869 assert!(r.is_local());
3870 assert_eq!(r.commands.len(), 2);
3871 assert_eq!(r.timeout_minutes, 5);
3872 std::fs::write(&path, "[release]\nmode = \"local\"\nbogus = 1\n").unwrap();
3873 assert!(Config::load(&path).is_err());
3874 std::fs::write(&path, "[release]\nmode = \"gha\"\n").unwrap();
3875 assert!(Config::load(&path).is_err());
3876 }
3877
3878 #[test]
3879 fn pre_gate_defaults_to_empty_and_the_starter_documents_it() {
3880 let dir = tempfile::tempdir().unwrap();
3881 let path = dir.path().join("magi.toml");
3882 std::fs::write(&path, Config::starter_toml()).unwrap();
3883 assert!(Config::load(&path).unwrap().verify.pre_gate.is_empty());
3884 assert!(Config::starter_toml().contains("# pre_gate = []"));
3885 }
3886
3887 #[test]
3888 fn release_version_files_parse_default_empty_and_are_validated() {
3889 let dir = tempfile::tempdir().unwrap();
3890 let path = dir.path().join("magi.toml");
3891 std::fs::write(&path, "").unwrap();
3892 assert!(
3893 Config::load(&path)
3894 .unwrap()
3895 .release
3896 .version_files
3897 .is_empty()
3898 );
3899 std::fs::write(
3900 &path,
3901 "[release]\nversion_files = [\n{ path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n{ path = \"package.json\", kind = \"json\" },\n]\n",
3902 )
3903 .unwrap();
3904 let files = Config::load(&path).unwrap().release.version_files;
3905 assert_eq!(files.len(), 2);
3906 assert_eq!(files[1].kind, VersionKind::Json);
3907 for bad in [
3908 "{ path = \"package.json\", kind = \"json\" }",
3909 "{ path = \"../Cargo.toml\", kind = \"cargo\" }",
3910 "{ path = \"Cargo.toml\", kind = \"cargo\", extra = 1 }",
3911 "{ path = \"Cargo.toml\", kind = \"yaml\" }",
3912 ] {
3913 std::fs::write(&path, format!("[release]\nversion_files = [{bad}]\n")).unwrap();
3914 assert!(Config::load(&path).is_err(), "{bad}");
3915 }
3916 assert!(Config::starter_toml().contains("# version_files = ["));
3917 }
3918
3919 #[test]
3920 fn starter_toml_explains_inherited_and_explicit_verify_timeouts() {
3921 let starter = Config::starter_toml();
3922 assert!(starter.contains("When timeout_verify is omitted, E2E and"));
3923 assert!(starter.contains("verification independent if timeout_review changes later"));
3924 assert!(starter.contains("# timeout_verify = 1200"));
3925 }
3926
3927 #[test]
3928 fn starter_toml_documents_chat_personas() {
3929 let starter = Config::starter_toml();
3930 assert!(starter.contains("# [[talk.personas]]"));
3931 assert!(starter.contains("tone only"));
3932 }
3933
3934 #[test]
3935 fn talk_personas_parse_and_are_validated() {
3936 let dir = tempfile::tempdir().unwrap();
3937 let path = dir.path().join("magi.toml");
3938 std::fs::write(
3939 &path,
3940 "[[talk.personas]]\nid = \"rei\"\nname = \"Quiet\"\nprompt = \"Be brief.\"\n\n\
3941 [[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n",
3942 )
3943 .unwrap();
3944 let cfg = Config::load(&path).expect("loads");
3945 assert_eq!(cfg.talk.personas.len(), 2);
3946 let catalog = crate::persona::catalog(&cfg.talk.personas);
3947 let rei = catalog.iter().find(|p| p.id == "rei").unwrap();
3948 assert_eq!(
3949 (rei.name.as_str(), rei.prompt.as_str()),
3950 ("Quiet", "Be brief.")
3951 );
3952 assert_eq!(catalog.last().unwrap().id, "gendo");
3953
3954 for (body, needle) in [
3955 (
3956 "[[talk.personas]]\nid = \"\"\nname = \"n\"\nprompt = \"p\"\n",
3957 "empty `id`",
3958 ),
3959 (
3960 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \" \"\n",
3961 "empty `prompt`",
3962 ),
3963 (
3964 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n\
3965 [[talk.personas]]\nid = \"a\"\nname = \"m\"\nprompt = \"q\"\n",
3966 "more than once",
3967 ),
3968 (
3969 "[[talk.personas]]\nid = \"default\"\nname = \"n\"\nprompt = \"p\"\n",
3970 "cannot be redefined",
3971 ),
3972 ] {
3973 std::fs::write(&path, body).unwrap();
3974 let err = format!("{:#}", Config::load(&path).unwrap_err());
3975 assert!(err.contains(needle), "{needle}: {err}");
3976 }
3977 }
3978
3979 #[test]
3980 fn talk_operator_name_is_trimmed_and_validated() {
3981 let dir = tempfile::tempdir().unwrap();
3982 let path = dir.path().join("magi.toml");
3983 let load = |body: &str| {
3984 std::fs::write(&path, body).unwrap();
3985 Config::load(&path)
3986 };
3987 let ok = load("[talk]\noperator_name = \" Commander \"\n").expect("ok");
3988 assert_eq!(ok.talk.operator_name(), Some("Commander"));
3989 let blank = load("[talk]\noperator_name = \" \"\n").expect("blank");
3990 assert_eq!(blank.talk.operator_name(), None);
3991 assert!(load("[talk]\noperator_name = \"a\\nb\"\n").is_err());
3992 let long = "x".repeat(65);
3993 assert!(load(&format!("[talk]\noperator_name = \"{long}\"\n")).is_err());
3994 }
3995
3996 #[test]
3997 fn talk_persona_icon_parses_and_a_bad_shape_keeps_config_usable() {
3998 let dir = tempfile::tempdir().unwrap();
3999 let load = |body: &str| {
4000 let path = dir.path().join("c.toml");
4001 std::fs::write(&path, body).unwrap();
4002 Config::load(&path)
4003 };
4004 let ok = load(
4005 "[[talk.personas]]\nid = \"rei\"\nicon = \"~/rei.png\"\n\n\
4006 [[talk.personas]]\nid = \"default\"\nicon = \"data:image/png;base64,AAAA\"\n",
4007 )
4008 .unwrap();
4009 let c = crate::persona::catalog(&ok.talk.personas);
4010 assert_eq!(c[0].icon.as_deref(), Some("data:image/png;base64,AAAA"));
4011 assert_eq!(c[2].icon.as_deref(), Some("~/rei.png"));
4012 assert!(c[2].prompt.contains("Rei"), "built-in voice kept");
4013 let oversized = format!(
4014 "data:image/png;base64,{}",
4015 "A".repeat(crate::persona_icon::ICON_MAX_BYTES)
4016 );
4017 for bad in ["", "rei.png", "/a/b.svg", "/a/../b.png", &oversized] {
4018 for (id, fields) in [
4019 ("rei", ""),
4020 ("default", ""),
4021 ("custom", "name = \"Custom\"\nprompt = \"Keep calm\"\n"),
4022 ] {
4023 let body = format!("[[talk.personas]]\nid = \"{id}\"\nicon = \"{bad}\"\n{fields}");
4024 let cfg = load(&body).expect("bad icon must not invalidate config");
4025 let persona = crate::persona::find(&cfg.talk.personas, id).unwrap();
4026 assert_eq!(persona.id, id);
4027 assert!(crate::persona_icon::load(bad).is_err());
4028 }
4029 }
4030 let doc = Config::starter_toml();
4031 assert!(doc.contains("# icon = "));
4032 }
4033
4034 #[test]
4035 fn talk_personas_in_two_layers_are_refused() {
4036 let dir = tempfile::tempdir().unwrap();
4037 let machine = dir.path().join("machine.toml");
4038 let repo = dir.path().join("repo.toml");
4039 let one = "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n";
4040 std::fs::write(&machine, one).unwrap();
4041 std::fs::write(&repo, one.replace("\"a\"", "\"b\"")).unwrap();
4042 let err = format!("{:#}", Config::load_layers(&[machine, repo]).unwrap_err());
4043 assert!(err.contains("talk.personas"), "{err}");
4044 }
4045
4046 #[test]
4047 fn starter_toml_documents_role_lists_as_backup_order() {
4048 let starter = Config::starter_toml();
4049 assert!(starter.contains("also an ordered backup list"));
4050 assert!(starter.contains("codex then sonnet are spares"));
4051 }
4052
4053 #[test]
4057 fn a_repository_can_declare_a_linear_history_merge_style() {
4058 let dir = tempfile::tempdir().unwrap();
4059 let path = dir.path().join("magi.toml");
4060 std::fs::write(&path, "[merge]\nmode = \"none\"\nstyle = \"squash\"\n").unwrap();
4061 let parsed = Config::load(&path).expect("config must load");
4062 assert_eq!(parsed.merge.style, MergeStyle::Squash);
4063 }
4064
4065 #[test]
4066 fn later_layers_win_and_vars_render() {
4067 let dir = tempfile::tempdir().unwrap();
4068 let machine = dir.path().join("machine.toml");
4069 let project = dir.path().join("magi.toml");
4070 std::fs::write(
4072 &machine,
4073 "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
4074 [graph]\ncandidates = 3\nmax_parallel = 8\n[verify]\nbuild_cache = \"shared\"\n",
4075 )
4076 .unwrap();
4077 std::fs::write(
4080 &project,
4081 "[vars]\ncache = \"/shared\"\n\n\
4082 [graph]\ncandidates = 2\n\n\
4083 [verify]\nbuild_cache = \"isolated\"\n\
4084 gate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
4085 )
4086 .unwrap();
4087
4088 let cfg = Config::load_layers(&[machine, project]).expect("layered load");
4089 assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
4090 assert_eq!(cfg.graph.implementers, 2, "project layer wins");
4091 assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
4092 assert_eq!(cfg.verify.build_cache, BuildCache::Isolated);
4093 assert_eq!(
4094 cfg.verify.gate,
4095 ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
4096 );
4097 assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
4099 }
4100
4101 #[test]
4102 fn saved_config_without_a_build_cache_policy_remains_shared() {
4103 let saved: Config = serde_json::from_str(r#"{"verify":{"gate":["cargo test"]}}"#).unwrap();
4104 assert_eq!(saved.verify.build_cache, BuildCache::Shared);
4105 }
4106
4107 #[test]
4108 fn talk_defaults_to_an_hour_and_an_unwritten_config_still_gets_it() {
4109 let g = Graph::default();
4113 assert_eq!(g.timeout_talk, 3600);
4114
4115 let dir = tempfile::tempdir().unwrap();
4116 let path = dir.path().join("magi.toml");
4117 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
4118 let cfg = Config::load(&path).expect("must load without timeout_talk set");
4119 assert_eq!(cfg.graph.timeout_talk, 3600);
4120 }
4121
4122 #[test]
4123 fn an_overridden_talk_timeout_reaches_the_loaded_config() {
4124 let dir = tempfile::tempdir().unwrap();
4125 let path = dir.path().join("magi.toml");
4126 std::fs::write(&path, "[graph]\ntimeout_talk = 120\n").unwrap();
4127 let cfg = Config::load(&path).expect("must load");
4128 assert_eq!(cfg.graph.timeout_talk, 120);
4129 }
4130
4131 #[test]
4132 fn the_disk_defaults_are_the_measurements_made_up_front() {
4133 let cfg = Config::default();
4134 assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
4135 assert!(cfg.disk.auto_fold);
4136 assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
4137 assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
4138 }
4139
4140 #[test]
4141 fn an_unset_disk_section_is_the_safe_default() {
4142 let dir = tempfile::tempdir().unwrap();
4143 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
4144 let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
4145 assert_eq!(cfg.disk, Disk::default());
4146 }
4147
4148 #[test]
4149 fn env_is_available_to_templates_with_a_default() {
4150 let dir = tempfile::tempdir().unwrap();
4151 let path = dir.path().join("magi.toml");
4152 std::fs::write(
4160 &path,
4161 "[verify]\n\
4162 gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
4163 \"populated={{ env | length > 0 }}\"]\n",
4164 )
4165 .unwrap();
4166 let cfg = Config::load(&path).expect("env lookup must render");
4167 assert_eq!(cfg.verify.gate[0], "cache=fallback");
4168 assert_eq!(cfg.verify.gate[1], "populated=true");
4169 }
4170
4171 #[test]
4172 fn a_broken_template_names_the_file() {
4173 let dir = tempfile::tempdir().unwrap();
4174 let path = dir.path().join("magi.toml");
4175 std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
4176 let err = Config::load(&path).expect_err("must not silently ignore");
4177 assert!(err.to_string().contains("teravars"), "{err}");
4178 }
4179
4180 #[test]
4181 fn tera_syntax_in_comments_is_inert() {
4182 let dir = tempfile::tempdir().unwrap();
4186 let path = dir.path().join("magi.toml");
4187 std::fs::write(
4188 &path,
4189 "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
4190 [graph]\ncandidates = 2\n",
4191 )
4192 .unwrap();
4193 let cfg = Config::load(&path).expect("comments must be inert, not rendered");
4194 assert_eq!(cfg.graph.implementers, 2);
4195 }
4196
4197 #[test]
4198 fn agent_turn_cap_round_trips_and_never_extends_the_budget() {
4199 use std::time::Duration;
4200
4201 let mut s: AgentSpec =
4202 toml::from_str("id = 'slow'\nkind = 'command'\ncommand = ['true']\n").unwrap();
4203 let budget = Duration::from_millis(1500);
4204 assert_eq!(s.max_turn_secs, None);
4205 assert_eq!(s.turn_timeout(budget), budget);
4206 assert!(!toml::to_string(&s).unwrap().contains("max_turn_secs"));
4207 for (cap, expected) in [
4208 (1, Duration::from_secs(1)),
4209 (2, budget),
4210 (0, Duration::ZERO),
4211 ] {
4212 s.max_turn_secs = Some(cap);
4213 let saved = toml::to_string(&s).unwrap();
4214 let loaded: AgentSpec = toml::from_str(&saved).unwrap();
4215 assert_eq!(loaded.max_turn_secs, Some(cap));
4216 assert_eq!(loaded.turn_timeout(budget), expected);
4217 }
4218 }
4219
4220 #[test]
4221 fn opencode_defaults_to_file_delivery() {
4222 let mut s = spec("oc");
4223 s.kind = AgentKind::Opencode;
4224 assert_eq!(s.delivery(), Delivery::File);
4225 s.prompt_delivery = Some(Delivery::Argv);
4226 assert_eq!(s.delivery(), Delivery::Argv);
4227 }
4228 #[test]
4229 fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
4230 let g = Graph::default();
4235 assert!(
4236 g.land,
4237 "stopping at an open PR left the watching to a human"
4238 );
4239 assert!(
4240 g.land_approval,
4241 "on-by-default land is only defensible while this is also on"
4242 );
4243 assert!(g.land_rounds > 0, "a loop with no budget never terminates");
4244 assert!(
4245 g.hold_contested_merge,
4246 "a contested hand-off must still reach a human when approvals are off"
4247 );
4248 }
4249 #[test]
4250 fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
4251 let dir = tempfile::tempdir().unwrap();
4255 let machine = dir.path().join("machine.toml");
4256 let repo = dir.path().join("magi.toml");
4257 std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
4258 std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
4259
4260 let err = Config::load_layers(&[machine.clone(), repo.clone()])
4261 .expect_err("two layers naming one array must not merge silently");
4262 assert_eq!(
4263 err.downcast_ref::<ConfigFailure>().unwrap().stage,
4264 "config-merge"
4265 );
4266 let err = err.to_string();
4267 assert!(err.contains("roles.implementers"), "{err}");
4268 assert!(err.contains("machine.toml"), "{err}");
4271 assert!(err.contains("magi.toml"), "{err}");
4272 }
4273
4274 #[test]
4275 fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
4276 let dir = tempfile::tempdir().unwrap();
4279 let machine = dir.path().join("machine.toml");
4280 let repo = dir.path().join("magi.toml");
4281 std::fs::write(&machine, "[roles]\nchatter = \"opus\"\n").unwrap();
4282 std::fs::write(
4283 &repo,
4284 "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
4285 [roles]\nimplementers = [\"oc\"]\n",
4286 )
4287 .unwrap();
4288
4289 let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
4290 assert_eq!(primary(cfg.roles.chatter.as_ref()), Some("opus"));
4291 assert_eq!(cfg.roles.implementers, ["oc"]);
4292 assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
4293 }
4294
4295 #[test]
4296 fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
4297 let dir = tempfile::tempdir().unwrap();
4300 let machine = dir.path().join("machine.toml");
4301 let repo = dir.path().join("magi.toml");
4302 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
4303 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4304
4305 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4306 assert_eq!(
4307 cfg.verify.gate,
4308 [
4309 "editorconfig-checker".to_owned(),
4310 "cargo make check".to_owned()
4311 ],
4312 "low-priority (machine) command first, high-priority (repo) command after"
4313 );
4314 }
4315
4316 fn load_one(body: &str) -> Result<Config> {
4317 let dir = tempfile::tempdir().unwrap();
4318 let path = dir.path().join("magi.toml");
4319 std::fs::write(&path, body).unwrap();
4320 Config::load_layers(&[path])
4321 }
4322
4323 #[test]
4324 fn pre_clean_config_is_strict_and_single_layer() {
4325 assert!(Config::default().worktree.pre_clean.is_empty());
4326 let good = load_one("[worktree]\npre_clean = [{run = 'cleanup', timeout_secs = 60}]\n");
4327 assert_eq!(good.unwrap().worktree.pre_clean[0].timeout_secs, Some(60));
4328 for bad in [
4329 "{}",
4330 "{run = ''}",
4331 "{run = ' ', timeout_secs = 2}",
4332 "{run = 'x', timeout_secs = 0}",
4333 "{run = 'x', timeout_secs = -1}",
4334 "{copy = 'cache'}",
4335 "{run = 'x', optional = true}",
4336 "'x'",
4337 ] {
4338 assert!(
4339 load_one(&format!("[worktree]\npre_clean = [{bad}]\n")).is_err(),
4340 "{bad}"
4341 );
4342 }
4343 let dir = tempfile::tempdir().unwrap();
4344 let a = dir.path().join("a.toml");
4345 let b = dir.path().join("b.toml");
4346 for path in [&a, &b] {
4347 std::fs::write(path, "[worktree]\npre_clean = [{run = 'cleanup'}]\n").unwrap();
4348 }
4349 assert!(
4350 Config::load_layers(&[a, b])
4351 .unwrap_err()
4352 .to_string()
4353 .contains("worktree.pre_clean")
4354 );
4355 }
4356
4357 #[test]
4358 fn worktree_setup_defaults_to_empty_and_parses_steps() {
4359 assert!(Config::default().worktree.setup.is_empty());
4360 let cfg = load_one(
4361 "[worktree]\nsetup = [\n { copy = \".env.example -> .env\" },\n \
4362 { copy = \"x\", optional = true },\n { run = \"true\", timeout_secs = 5 },\n]\n",
4363 )
4364 .unwrap();
4365 assert_eq!(cfg.worktree.setup.len(), 3);
4366 assert!(cfg.worktree.setup[1].optional);
4367 assert_eq!(cfg.worktree.setup[2].timeout_secs, Some(5));
4368 }
4369
4370 #[test]
4371 fn worktree_setup_rejects_malformed_steps() {
4372 for bad in [
4373 "{ copy = \"a\", run = \"b\" }",
4374 "{ optional = true }",
4375 "{ copy = \"a -> ../b\" }",
4376 "{ copy = \"a -> /abs\" }",
4377 "{ copy = \"a -> .git/config\" }",
4378 "{ run = \"b\", optional = true }",
4379 "{ copy = \"a\", timeout_secs = 3 }",
4380 "{ run = \"b\", bogus = 1 }",
4381 ] {
4382 let body = format!("[worktree]\nsetup = [{bad}]\n");
4383 assert!(load_one(&body).is_err(), "{bad}");
4384 }
4385 }
4386
4387 #[test]
4388 fn worktree_setup_in_two_layers_is_refused() {
4389 let dir = tempfile::tempdir().unwrap();
4390 let machine = dir.path().join("machine.toml");
4391 let repo = dir.path().join("magi.toml");
4392 std::fs::write(&machine, "[worktree]\nsetup = [{ run = \"a\" }]\n").unwrap();
4393 std::fs::write(&repo, "[worktree]\nsetup = [{ run = \"b\" }]\n").unwrap();
4394 assert!(Config::load_layers(&[machine, repo]).is_err());
4395 }
4396
4397 #[test]
4398 fn starter_toml_documents_worktree_setup() {
4399 let starter = Config::starter_toml();
4400 assert!(starter.contains("# [worktree]") && starter.contains("setup = ["));
4401 let body = starter.replace("# [worktree]", "[worktree]");
4403 let mut out = String::new();
4404 let mut live = false;
4405 for line in body.lines() {
4406 if line == "[worktree]" {
4407 live = true;
4408 } else if live && !line.starts_with("# ") {
4409 live = false;
4410 }
4411 out.push_str(&if live {
4412 line.replacen("# ", "", 1)
4413 } else {
4414 line.to_owned()
4415 });
4416 out.push('\n');
4417 }
4418 let cfg = load_one(&out).expect("uncommented example loads");
4419 assert_eq!(cfg.worktree.setup.len(), 3);
4420 }
4421
4422 #[test]
4423 fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
4424 let dir = tempfile::tempdir().unwrap();
4425 let machine = dir.path().join("machine.toml");
4426 let repo = dir.path().join("magi.toml");
4427 std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
4428 std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
4429
4430 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4431 assert_eq!(
4432 cfg.verify.e2e,
4433 ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
4434 );
4435 }
4436
4437 #[test]
4438 fn two_layers_declaring_repos_roots_are_both_scanned() {
4439 let dir = tempfile::tempdir().unwrap();
4440 let machine = dir.path().join("machine.toml");
4441 let repo = dir.path().join("magi.toml");
4442 std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
4443 std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
4444
4445 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4446 assert_eq!(
4447 cfg.repos.roots,
4448 [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
4449 );
4450 }
4451
4452 #[test]
4453 fn duplicate_gate_commands_across_layers_both_run() {
4454 let dir = tempfile::tempdir().unwrap();
4457 let machine = dir.path().join("machine.toml");
4458 let repo = dir.path().join("magi.toml");
4459 std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
4460 std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
4461
4462 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
4463 assert_eq!(
4464 cfg.verify.gate,
4465 ["same-command".to_owned(), "same-command".to_owned()]
4466 );
4467 }
4468
4469 #[test]
4470 fn notify_command_is_still_refused_across_two_layers() {
4471 let dir = tempfile::tempdir().unwrap();
4473 let machine = dir.path().join("machine.toml");
4474 let repo = dir.path().join("magi.toml");
4475 std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
4476 std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
4477
4478 let err = Config::load_layers(&[machine.clone(), repo.clone()])
4479 .expect_err("an argv split across layers must not concatenate");
4480 assert_eq!(
4481 err.downcast_ref::<ConfigFailure>().unwrap().stage,
4482 "config-merge"
4483 );
4484 let err = err.to_string();
4485 assert!(err.contains("notify.command"), "{err}");
4486 assert!(err.contains("machine.toml"), "{err}");
4487 assert!(err.contains("magi.toml"), "{err}");
4488 }
4489
4490 #[test]
4491 fn one_layer_declaring_verify_gate_runs_unchanged() {
4492 let dir = tempfile::tempdir().unwrap();
4495 let path = dir.path().join("magi.toml");
4496 std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4497
4498 let cfg = Config::load(&path).expect("single layer must still load");
4499 assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
4500 }
4501
4502 #[test]
4503 fn layered_parse_failures_name_the_failing_input() {
4504 let dir = tempfile::tempdir().unwrap();
4505 let a = dir.path().join("a.toml");
4506 let b = dir.path().join("b.toml");
4507 std::fs::write(&a, "[graph").unwrap();
4508 std::fs::write(&b, "[verify").unwrap();
4509 let paths = [a.clone(), b.clone()];
4510 let first = Config::load_layers(&paths).unwrap_err();
4511 let first_cause = first.downcast_ref::<ConfigFailure>().unwrap();
4512 assert_eq!(first_cause.stage, "config-parse");
4513 assert_eq!(first_cause.target, serde_json::to_string(&[&a]).unwrap());
4514 std::fs::write(&a, "").unwrap();
4515 let second = Config::load_layers(&paths).unwrap_err();
4516 let second_cause = second.downcast_ref::<ConfigFailure>().unwrap();
4517 assert_eq!(second_cause.stage, "config-parse");
4518 assert_eq!(second_cause.target, serde_json::to_string(&[&b]).unwrap());
4519 assert_ne!(first_cause.target, second_cause.target);
4520 }
4521
4522 #[test]
4523 fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
4524 let dir = tempfile::tempdir().unwrap();
4525 let machine = dir.path().join("machine.toml");
4526 let repo = dir.path().join("magi.toml");
4527 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
4528 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
4529 let paths = vec![machine.clone(), repo.clone()];
4530
4531 let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
4532 let described =
4533 Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
4534 assert!(described.contains("editorconfig-checker && cargo make check"));
4535 assert!(
4536 described.contains(&machine.display().to_string()),
4537 "{described}"
4538 );
4539 assert!(
4540 described.contains(&repo.display().to_string()),
4541 "{described}"
4542 );
4543
4544 let single = vec![repo.clone()];
4546 let solo_cfg = Config::load_layers(&single).expect("single layer loads");
4547 let solo_described =
4548 Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
4549 assert_eq!(solo_described, "cargo make check");
4550 }
4551
4552 mod remote_layers {
4553 use super::*;
4554
4555 fn git(dir: &Path, args: &[&str]) {
4556 use crate::proc::Quiet as _;
4557 let out = std::process::Command::new("git")
4558 .args(args)
4559 .quiet()
4560 .current_dir(dir)
4561 .output()
4562 .unwrap();
4563 assert!(out.status.success(), "git {args:?}: {out:?}");
4564 }
4565
4566 fn fixture(remote: &str, disk: &str) -> (tempfile::TempDir, PathBuf) {
4569 let tmp = tempfile::tempdir().unwrap();
4570 let bare = tmp.path().join("o.git");
4571 git(tmp.path(), &["init", "--bare", "-b", "trunk", "o.git"]);
4572 let repo = tmp.path().join("repo");
4573 std::fs::create_dir_all(&repo).unwrap();
4574 git(&repo, &["init", "-b", "trunk"]);
4575 git(&repo, &["config", "user.name", "t"]);
4576 git(&repo, &["config", "user.email", "t@example.com"]);
4577 std::fs::write(repo.join("magi.toml"), remote).unwrap();
4578 git(&repo, &["add", "-A"]);
4579 git(&repo, &["commit", "-m", "x"]);
4580 git(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
4581 git(&repo, &["push", "origin", "trunk"]);
4582 git(&repo, &["fetch", "origin"]);
4583 git(&repo, &["remote", "set-head", "origin", "trunk"]);
4584 std::fs::write(repo.join("magi.toml"), disk).unwrap();
4585 (tmp, repo)
4586 }
4587
4588 #[tokio::test]
4589 async fn branch_owner_holds_only_add_literal_true_values() {
4590 for (text, expected) in [
4591 ("[graph]\nland_approval = true\n", true),
4592 ("[graph]\nland_approval = false\n", false),
4593 ("[graph]\nland = true\n", false),
4594 ("[graph\n", false),
4595 ("[graph]\nland_approval = \"yes\"\n", false),
4596 ("[graph]\nland_approval = 1\n", false),
4597 ] {
4598 let (_tmp, repo) = fixture(text, "[graph]\nland_approval = false\n");
4599 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
4600 let (holds, _) = branch_owner_holds(&repo, &head).await;
4601 assert_eq!(
4602 holds.contains(&(OwnerHold::LandApproval, "magi.toml".into())),
4603 expected
4604 );
4605 assert!(
4606 !holds
4607 .iter()
4608 .any(|(h, _)| *h == OwnerHold::HoldContestedMerge)
4609 );
4610 for base in [false, true] {
4611 let mut cfg = Config::default();
4612 cfg.graph.land_approval = base;
4613 let mut state = crate::run::RunState::new(
4614 repo.clone(),
4615 "trunk".into(),
4616 head.clone(),
4617 "review".into(),
4618 cfg,
4619 );
4620 state.observe_branch_owner_holds(&head).await;
4621 assert!(
4622 state.branch_owner_holds.is_empty(),
4623 "competition candidates are excluded"
4624 );
4625 state.reviewed_commits = Some(Vec::new());
4626 state.observe_branch_owner_holds(&head).await;
4627 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base || expected);
4628 }
4629 }
4630 }
4631
4632 #[tokio::test]
4633 async fn branch_owner_holds_missing_and_unreadable_preserve_base() {
4634 let (_tmp, repo) = fixture(
4635 "[graph]\nland_approval = true\n",
4636 "[graph]\nland_approval = true\n",
4637 );
4638 git(&repo, &["rm", "magi.toml"]);
4639 std::fs::create_dir(repo.join(".magi")).unwrap();
4640 std::fs::write(
4641 repo.join(".magi/config.toml"),
4642 "[graph]\nhold_contested_merge = true\n",
4643 )
4644 .unwrap();
4645 git(&repo, &["add", "."]);
4646 git(&repo, &["commit", "-m", "nested hold"]);
4647 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
4648 let (holds, _) = branch_owner_holds(&repo, &head).await;
4649 assert_eq!(
4650 holds,
4651 [(OwnerHold::HoldContestedMerge, ".magi/config.toml".into())]
4652 );
4653 let (holds, diagnostics) =
4654 branch_owner_holds(&repo, "0000000000000000000000000000000000000000").await;
4655 assert!(holds.is_empty());
4656 assert!(!diagnostics.is_empty());
4657 let (holds, diagnostics) = branch_owner_holds(&repo, "").await;
4658 assert!(holds.is_empty());
4659 assert!(!diagnostics.is_empty());
4660 for base in [false, true] {
4661 let mut cfg = Config::default();
4662 cfg.graph.land_approval = base;
4663 let mut state = crate::run::RunState::new(
4664 repo.clone(),
4665 "trunk".into(),
4666 head.clone(),
4667 "review".into(),
4668 cfg,
4669 );
4670 state.reviewed_commits = Some(Vec::new());
4671 state.observe_branch_owner_holds(&head).await;
4672 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
4673 state
4674 .observe_branch_owner_holds("0000000000000000000000000000000000000000")
4675 .await;
4676 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
4677 }
4678 }
4679
4680 #[test]
4681 fn reads_the_remote_blob_not_the_working_tree() {
4682 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4683 let (cfg, _) = Config::discover(&repo, None).unwrap();
4684 assert_eq!(cfg.graph.implementers, 2);
4685 }
4686
4687 #[test]
4688 fn detached_head_still_reads_the_remote() {
4689 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4690 git(&repo, &["checkout", "--detach"]);
4691 let (cfg, _) = Config::discover(&repo, None).unwrap();
4692 assert_eq!(cfg.graph.implementers, 2);
4693 }
4694
4695 #[test]
4696 fn a_missing_ref_is_an_error_not_a_fallback() {
4697 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
4698 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
4699 let err = format!("{:#}", Config::discover(&repo, None).unwrap_err());
4700 assert!(err.contains("origin"), "{err}");
4701 }
4702
4703 #[test]
4704 fn merge_base_in_the_checkout_locates_the_ref() {
4705 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
4706 assert!(Config::discover(&repo, None).is_err());
4707 }
4708
4709 #[test]
4710 fn the_magi_dir_layer_is_read_too() {
4711 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4712 std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
4713 std::fs::create_dir_all(repo.join(".magi")).unwrap();
4714 std::fs::write(repo.join(".magi/config.toml"), "[graph]\njudges = 3\n").unwrap();
4715 git(&repo, &["add", "-A"]);
4716 git(&repo, &["commit", "-m", "y"]);
4717 git(&repo, &["push", "origin", "trunk"]);
4718 git(&repo, &["fetch", "origin"]);
4719 let (cfg, layers) = Config::discover(&repo, None).unwrap();
4720 assert_eq!((cfg.graph.implementers, cfg.graph.judges), (2, 3));
4721 assert_eq!(layers.len(), 2);
4722 }
4723
4724 #[test]
4725 fn an_include_in_a_repository_layer_resolves_against_the_same_commit() {
4726 let (_t, repo) = fixture("include = [\"gate.toml\"]\n", "");
4727 std::fs::write(repo.join("magi.toml"), "include = [\"gate.toml\"]\n").unwrap();
4728 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 2\n").unwrap();
4729 git(&repo, &["add", "-A"]);
4730 git(&repo, &["commit", "-m", "inc"]);
4731 git(&repo, &["push", "origin", "trunk"]);
4732 git(&repo, &["fetch", "origin"]);
4733 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 9\n").unwrap();
4735 let (cfg, _) = Config::discover(&repo, None).unwrap();
4736 assert_eq!(cfg.graph.implementers, 2);
4737 }
4738
4739 #[test]
4740 fn a_machine_layer_base_is_rendered_before_locating_the_ref() {
4741 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
4742 let m = t.path().join("machine.toml");
4743 std::fs::write(
4744 &m,
4745 "[merge]\nbase = \"{{ env.MAGI_TEST_NO_SUCH | default(value='trunk') }}\"\n",
4746 )
4747 .unwrap();
4748 let (remote, base) = {
4749 let probe = probe_merge(&m, &repo).unwrap();
4750 (probe.remote, probe.base)
4751 };
4752 assert_eq!((remote, base), (None, Some("trunk".to_owned())));
4753 }
4754
4755 #[test]
4756 fn a_machine_layer_base_sees_the_checkouts_repo_name() {
4757 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4758 let m = t.path().join("machine.toml");
4759 std::fs::write(&m, "[merge]\nbase = \"{{ repo_name }}\"\n").unwrap();
4760 let probe = probe_merge(&m, &repo).unwrap();
4761 assert_eq!(probe.base.as_deref(), Some("repo"));
4762 }
4763
4764 #[test]
4765 fn every_include_form_is_recognised() {
4766 assert!(declares_include("include = [\"a.toml\"]\n"));
4767 assert!(declares_include("\"include\" = [\"a.toml\"]\n"));
4768 assert!(declares_include("teravars = { include = [\"a.toml\"] }\n"));
4769 assert!(declares_include("[teravars]\ninclude = [\"a.toml\"]\n"));
4770 assert!(!declares_include("[graph]\ncandidates = 2\n"));
4771 }
4772
4773 #[test]
4774 fn an_explicit_config_is_read_as_named() {
4775 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4776 let own = t.path().join("own.toml");
4777 std::fs::write(&own, "[graph]\ncandidates = 4\n").unwrap();
4778 let (cfg, _) = Config::discover(&repo, Some(&own)).unwrap();
4779 assert_eq!(cfg.graph.implementers, 4);
4780 }
4781
4782 #[test]
4783 fn discover_fetched_fails_when_the_fetch_does() {
4784 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4785 std::fs::remove_dir_all(t.path().join("o.git")).unwrap();
4786 let rt = tokio::runtime::Builder::new_current_thread()
4787 .enable_all()
4788 .build()
4789 .unwrap();
4790 let err = rt
4791 .block_on(Config::discover_fetched(&repo, None))
4792 .unwrap_err();
4793 assert!(format!("{err:#}").contains("fetch"), "{err:#}");
4794 }
4795
4796 #[test]
4797 fn fetch_and_remote_parse_failures_have_distinct_verified_causes() {
4798 let (tmp, repo) = fixture("[graph\ncandidates = 2\n", "");
4799 let remote = tmp.path().join("o.git");
4800 let offline = tmp.path().join("offline.git");
4801 std::fs::rename(&remote, &offline).unwrap();
4802 let rt = tokio::runtime::Builder::new_current_thread()
4803 .enable_all()
4804 .build()
4805 .unwrap();
4806 let fetch = rt
4807 .block_on(Config::discover_fetched(&repo, None))
4808 .unwrap_err();
4809 let fetch_cause = fetch.downcast_ref::<ConfigFailure>().unwrap();
4810 assert_eq!(fetch_cause.stage, "config-fetch");
4811 assert_eq!(fetch_cause.target, "origin/trunk");
4812
4813 std::fs::rename(&offline, &remote).unwrap();
4814 let parse = rt
4815 .block_on(Config::discover_fetched(&repo, None))
4816 .unwrap_err();
4817 let parse_cause = parse.downcast_ref::<ConfigFailure>().unwrap();
4818 assert_eq!(parse_cause.stage, "config-parse");
4819 assert!(parse_cause.target.contains("magi.toml"));
4820 assert!(
4821 !parse_cause.target.contains("/magi/config/"),
4822 "cache commit paths are incidental"
4823 );
4824 assert_ne!(fetch_cause.stage, parse_cause.stage);
4825 }
4826
4827 #[test]
4828 fn discover_fetched_survives_a_fetch_that_leaves_no_origin_head() {
4829 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
4832 git(&repo, &["remote", "set-head", "origin", "-d"]);
4833 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
4834 git(
4835 &repo,
4836 &["config", "remote.origin.followRemoteHEAD", "never"],
4837 );
4838 let rt = tokio::runtime::Builder::new_current_thread()
4839 .enable_all()
4840 .build()
4841 .unwrap();
4842 let (cfg, _) = rt.block_on(Config::discover_fetched(&repo, None)).unwrap();
4843 assert_eq!(cfg.graph.implementers, 2);
4844 }
4845
4846 #[test]
4847 fn a_non_git_directory_reads_its_files() {
4848 let dir = tempfile::tempdir().unwrap();
4849 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 4\n").unwrap();
4850 let (cfg, _) = Config::discover(dir.path(), None).unwrap();
4851 assert_eq!(cfg.graph.implementers, 4);
4852 }
4853 }
4854
4855 #[test]
4856 fn github_language_defaults_to_english_and_accepts_japanese() {
4857 let default: Graph = toml::from_str("").unwrap();
4858 assert_eq!(default.github_language, "en");
4859 assert!(default.github_english() && default.language_gate());
4860 let ja: Graph = toml::from_str("github_language = \"ja\"").unwrap();
4861 assert!(!ja.github_english() && !ja.language_gate());
4862 let only_ops: Graph = toml::from_str("language = \"ja\"").unwrap();
4864 assert!(only_ops.language_gate());
4865 let off: Graph = toml::from_str("github_text_guard = false").unwrap();
4866 assert!(!off.language_gate() && off.github_english());
4867 assert!(Config::starter_toml().contains("github_language = \"en\""));
4868 }
4869}