1use std::collections::BTreeMap;
47use std::path::{Path, PathBuf};
48
49use anyhow::{Context as _, Result, bail};
50use serde::{Deserialize, Serialize};
51
52#[derive(Debug, thiserror::Error)]
55#[error("{stage}: {target}")]
56pub(crate) struct ConfigFailure {
57 pub(crate) stage: &'static str,
58 pub(crate) target: String,
59}
60
61impl ConfigFailure {
62 fn render(error: &teravars::Error, paths: &[PathBuf]) -> Self {
63 let stage = match error {
64 teravars::Error::Io(_) => "config-read",
65 teravars::Error::Toml(_) | teravars::Error::Extract(_) => "config-parse",
66 teravars::Error::Render(_) => "config-template",
67 teravars::Error::IncludeCycle { .. } | teravars::Error::IncludeConflict { .. } => {
68 "config-include"
69 }
70 _ => "config-render",
71 };
72 Self::layers(stage, paths)
73 }
74
75 fn layers(stage: &'static str, paths: &[PathBuf]) -> Self {
76 let targets: Vec<_> = paths
77 .iter()
78 .map(|path| {
79 path.ancestors()
82 .find(|p| p.join(REPO_MARKER).is_file())
83 .and_then(|root| path.strip_prefix(root).ok())
84 .unwrap_or(path)
85 .to_string_lossy()
86 .into_owned()
87 })
88 .collect();
89 Self {
90 stage,
91 target: serde_json::to_string(&targets).expect("config paths"),
92 }
93 }
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
98#[serde(rename_all = "lowercase")]
99pub enum AgentKind {
100 Claude,
102 Opencode,
104 Antigravity,
108 Codex,
112 Omp,
118 Command,
120}
121
122impl AgentKind {
123 pub fn program(self) -> Option<&'static str> {
125 match self {
126 Self::Claude => Some("claude"),
127 Self::Opencode => Some("opencode"),
128 Self::Antigravity => Some("agy"),
129 Self::Codex => Some("codex"),
130 Self::Omp => Some("omp"),
131 Self::Command => None,
132 }
133 }
134
135 pub fn as_str(self) -> &'static str {
137 match self {
138 Self::Claude => "claude",
139 Self::Opencode => "opencode",
140 Self::Antigravity => "antigravity",
141 Self::Codex => "codex",
142 Self::Omp => "omp",
143 Self::Command => "command",
144 }
145 }
146
147 pub const ALL: [Self; 6] = [
155 Self::Claude,
156 Self::Opencode,
157 Self::Antigravity,
158 Self::Codex,
159 Self::Omp,
160 Self::Command,
161 ];
162}
163
164#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
166#[serde(rename_all = "lowercase")]
167pub enum Delivery {
168 Stdin,
170 Argv,
172 File,
174}
175
176#[derive(Debug, Clone, Deserialize, Serialize)]
178#[serde(deny_unknown_fields)]
179pub struct AgentSpec {
180 pub id: String,
182 pub kind: AgentKind,
184 #[serde(default)]
186 pub model: Option<String>,
187 #[serde(default)]
190 pub command: Vec<String>,
191 #[serde(default)]
193 pub extra_args: Vec<String>,
194 #[serde(default)]
196 pub env: BTreeMap<String, String>,
197 #[serde(default)]
199 pub prompt_delivery: Option<Delivery>,
200 #[serde(default, skip_serializing_if = "Option::is_none")]
203 pub max_turn_secs: Option<u64>,
204}
205
206impl AgentSpec {
207 pub fn turn_timeout(&self, budget: std::time::Duration) -> std::time::Duration {
209 self.max_turn_secs.map_or(budget, |secs| {
210 budget.min(std::time::Duration::from_secs(secs))
211 })
212 }
213
214 pub fn delivery(&self) -> Delivery {
220 self.prompt_delivery.unwrap_or(match self.kind {
221 AgentKind::Claude | AgentKind::Command => Delivery::Stdin,
222 AgentKind::Codex => Delivery::Stdin,
226 AgentKind::Omp => Delivery::Stdin,
230 AgentKind::Opencode | AgentKind::Antigravity => Delivery::File,
231 })
232 }
233
234 pub fn display(&self) -> String {
236 match &self.model {
237 Some(m) => format!("{} ({}:{m})", self.id, self.kind.as_str()),
238 None => format!("{} ({})", self.id, self.kind.as_str()),
239 }
240 }
241}
242
243#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
250#[serde(untagged)]
251pub enum AgentChoice {
252 One(String),
254 Chain(Vec<String>),
256}
257
258impl AgentChoice {
259 pub fn ids(&self) -> Vec<&str> {
261 let all: Vec<&str> = match self {
262 Self::One(id) => vec![id.as_str()],
263 Self::Chain(ids) => ids.iter().map(String::as_str).collect(),
264 };
265 all.into_iter()
266 .map(str::trim)
267 .filter(|id| !id.is_empty())
268 .collect()
269 }
270
271 pub fn primary(&self) -> Option<&str> {
273 self.ids().into_iter().next()
274 }
275}
276
277impl From<&str> for AgentChoice {
278 fn from(id: &str) -> Self {
279 Self::One(id.to_owned())
280 }
281}
282
283pub fn primary(choice: Option<&AgentChoice>) -> Option<&str> {
285 choice.and_then(AgentChoice::primary)
286}
287
288#[derive(Debug, Clone, Default, Deserialize, Serialize)]
291#[serde(deny_unknown_fields, default)]
292pub struct Roles {
293 pub implementers: Vec<String>,
295 pub judges: Vec<String>,
297 pub reviewers: Vec<String>,
299 pub fixer: Option<AgentChoice>,
308 pub chatter: Option<AgentChoice>,
322 pub dupes_judge: Option<AgentChoice>,
326 pub conductor: Option<AgentChoice>,
339 pub advisors: Vec<String>,
350 pub synthesizer: Option<AgentChoice>,
363 pub language_judge: Option<AgentChoice>,
372}
373
374#[derive(Debug, Clone, Deserialize, Serialize)]
376#[serde(deny_unknown_fields, default)]
377pub struct Graph {
378 #[serde(rename = "editing_network", skip_serializing)]
382 pub retired_editing_network: Option<serde::de::IgnoredAny>,
383 pub github_text_guard: bool,
385 pub github_language: String,
391 #[serde(alias = "candidates")]
423 pub implementers: usize,
424 #[serde(default)]
426 pub selected_implementer: Option<String>,
427 pub judges: usize,
429 pub deliberate_rounds: usize,
431 pub reviewers: usize,
439 pub review_rounds: usize,
441 pub gate_fix_rounds: usize,
447 pub max_parallel: usize,
449 pub language: String,
451 pub sessions: bool,
459 pub timeout_implement: u64,
461 pub timeout_judge: u64,
463 pub timeout_review: u64,
465 pub timeout_verify: Option<u64>,
474 pub timeout_fix: u64,
476 pub timeout_talk: u64,
484 pub timeout_resource_wait: u64,
493 pub retries: usize,
495 pub worktree_root: Option<PathBuf>,
497 pub land: bool,
510 pub land_rounds: usize,
512 pub rerun_flaky_checks: bool,
520 pub land_approval: bool,
531 pub hold_contested_merge: bool,
542 pub question_routing: bool,
545 pub file_followups: bool,
552 pub release_deputy_followups: bool,
560 pub answer_timeout: u64,
564 pub incomplete_review: IncompleteReviewPolicy,
567 pub e2e_every_round: bool,
585 pub rerun_failed_e2e: bool,
597 pub advise: bool,
611 pub advisors: usize,
616 pub graft_runner_up: bool,
625}
626
627impl Default for Graph {
628 fn default() -> Self {
629 Self {
630 github_text_guard: true,
631 github_language: "en".into(),
632 implementers: 1,
633 selected_implementer: None,
634 retired_editing_network: None,
635 judges: 3,
636 deliberate_rounds: 1,
637 reviewers: 3,
638 review_rounds: 6,
639 gate_fix_rounds: 1,
640 max_parallel: 4,
641 language: "en".to_owned(),
642 sessions: true,
643 timeout_implement: 3600,
644 timeout_judge: 1200,
645 timeout_review: 1200,
646 timeout_verify: None,
647 timeout_fix: 1800,
648 timeout_talk: 3600,
649 timeout_resource_wait: 1800,
650 retries: 1,
651 worktree_root: None,
652 land: true,
653 land_rounds: 4,
654 rerun_flaky_checks: true,
655 land_approval: true,
656 hold_contested_merge: true,
657 question_routing: true,
658 file_followups: true,
659 release_deputy_followups: true,
660 answer_timeout: 86_400,
661 incomplete_review: IncompleteReviewPolicy::Block,
662 e2e_every_round: false,
663 rerun_failed_e2e: true,
664 advise: true,
665 advisors: 3,
666 graft_runner_up: true,
667 }
668 }
669}
670
671impl Graph {
672 pub fn verify_timeout(&self) -> u64 {
676 self.timeout_verify.unwrap_or(self.timeout_review)
677 }
678
679 pub fn language_gate(&self) -> bool {
682 self.github_text_guard && self.github_english()
683 }
684
685 pub fn github_english(&self) -> bool {
687 crate::lang::is_english(&self.github_language)
688 }
689}
690
691#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
698#[serde(rename_all = "lowercase")]
699pub enum IncompleteReviewPolicy {
700 Block,
704 Warn,
709}
710
711#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
713#[serde(rename_all = "lowercase")]
714pub enum LeakPolicy {
715 Warn,
717 Redact,
719 Fail,
721}
722
723#[derive(Debug, Clone, Deserialize, Serialize)]
730#[serde(deny_unknown_fields, default)]
731pub struct Blind {
732 pub commit_msg_hook: bool,
735 pub strip_lines: Vec<String>,
739 pub vendor_tokens: Vec<String>,
741 pub on_leak: LeakPolicy,
743 pub seed: Option<u64>,
746}
747
748impl Default for Blind {
749 fn default() -> Self {
750 Self {
751 commit_msg_hook: true,
752 strip_lines: [
753 "Co-Authored-By:",
754 "Signed-off-by:",
755 "Assisted-by:",
756 "Generated-by:",
757 "Generated with",
758 "\u{1f916}",
759 ]
760 .iter()
761 .map(|s| (*s).to_owned())
762 .collect(),
763 vendor_tokens: [
764 "claude",
765 "anthropic",
766 "codex",
767 "openai",
768 "chatgpt",
769 "gemini",
770 "grok",
771 "xai",
772 "copilot",
773 "opencode",
774 "qoder",
775 "cursor",
776 "\u{1f916}",
777 ]
778 .iter()
779 .map(|s| (*s).to_owned())
780 .collect(),
781 on_leak: LeakPolicy::Warn,
782 seed: None,
783 }
784 }
785}
786
787#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize, clap::ValueEnum)]
789#[serde(rename_all = "snake_case")]
790pub enum BuildCache {
791 #[default]
793 Shared,
794 Isolated,
796}
797
798impl std::fmt::Display for BuildCache {
799 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
800 f.write_str(match self {
801 Self::Shared => "shared",
802 Self::Isolated => "isolated",
803 })
804 }
805}
806
807#[derive(Debug, Clone, Default, Deserialize, Serialize)]
809#[serde(deny_unknown_fields, default)]
810pub struct Verify {
811 pub build_cache: BuildCache,
813 pub e2e: Vec<String>,
816 pub gate: Vec<String>,
818 #[serde(default)]
829 pub pre_gate: Vec<String>,
830 pub shell: Option<Vec<String>>,
833}
834
835impl Verify {
836 pub fn cache_dir(&self) -> Option<PathBuf> {
842 self.e2e
843 .iter()
844 .chain(self.gate.iter())
845 .find_map(|cmd| crate::disk::extract_cargo_target_dir(cmd))
846 }
847
848 pub fn cargo_targets(&self) -> Vec<crate::cache::Target> {
851 use crate::cache::Target;
852 let all: Vec<String> = self.e2e.iter().chain(self.gate.iter()).cloned().collect();
853 let mut targets: Vec<_> = crate::cache::extract_manifest_paths(&all)
854 .into_iter()
855 .map(Target::Manifest)
856 .collect();
857 for dir in all
858 .iter()
859 .chain(&self.pre_gate)
860 .filter_map(|cmd| crate::build_target::command::directory(cmd))
861 {
862 let target = Target::Directory(dir);
863 if !targets.contains(&target) {
864 targets.push(target);
865 }
866 }
867 targets
868 }
869}
870
871#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
873#[serde(deny_unknown_fields, default)]
874pub struct Worktree {
875 pub setup: Vec<SetupStep>,
878 pub pre_clean: Vec<PreCleanStep>,
880}
881
882#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
884#[serde(deny_unknown_fields)]
885pub struct PreCleanStep {
886 pub run: String,
888 pub timeout_secs: Option<u64>,
890}
891
892#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
894#[serde(deny_unknown_fields, default)]
895pub struct SetupStep {
896 pub copy: Option<String>,
899 pub optional: bool,
901 pub run: Option<String>,
903 pub timeout_secs: Option<u64>,
906}
907
908impl Worktree {
909 pub fn validate(&self) -> Result<()> {
911 for (i, step) in self.pre_clean.iter().enumerate() {
912 if step.run.trim().is_empty() || step.timeout_secs == Some(0) {
913 bail!(
914 "[worktree] pre_clean step {} requires a nonempty run and positive timeout",
915 i + 1
916 );
917 }
918 }
919 for (i, step) in self.setup.iter().enumerate() {
920 let n = i + 1;
921 match (&step.copy, &step.run) {
922 (Some(c), None) => {
923 if step.timeout_secs.is_some() {
924 bail!("[worktree] setup step {n}: `timeout_secs` applies to `run` only");
925 }
926 crate::worktree_setup::validate_copy(c)
927 .with_context(|| format!("[worktree] setup step {n}"))?;
928 }
929 (None, Some(r)) => {
930 if r.trim().is_empty() {
931 bail!("[worktree] setup step {n}: `run` is empty");
932 }
933 if step.optional {
934 bail!("[worktree] setup step {n}: `optional` applies to `copy` only");
935 }
936 }
937 _ => bail!("[worktree] setup step {n} must set exactly one of `copy` and `run`"),
938 }
939 }
940 Ok(())
941 }
942}
943
944#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
954#[serde(deny_unknown_fields, default)]
955pub struct Disk {
956 pub min_free_bytes: u64,
965 #[serde(skip_serializing_if = "Option::is_none")]
995 pub reclaim_free_bytes: Option<u64>,
996 pub auto_fold: bool,
1002 pub fold_grace_secs: u64,
1010 pub cache_limit_bytes: u64,
1022 pub worktree_limit_bytes: u64,
1024 pub worktree_reclaim_bytes: u64,
1028 pub retained_attempt_limit: usize,
1032}
1033
1034impl Disk {
1035 pub fn reclaim_threshold(&self) -> u64 {
1041 let floor = self.min_free_bytes;
1042 self.reclaim_free_bytes
1043 .map_or_else(|| floor.saturating_mul(2), |own| own.max(floor))
1044 }
1045}
1046
1047impl Default for Disk {
1048 fn default() -> Self {
1049 Self {
1050 min_free_bytes: 8 * 1024 * 1024 * 1024,
1051 reclaim_free_bytes: None,
1052 auto_fold: true,
1053 fold_grace_secs: 6 * 60 * 60,
1054 cache_limit_bytes: 10 * 1024 * 1024 * 1024,
1055 worktree_limit_bytes: 10 * 1024 * 1024 * 1024,
1056 worktree_reclaim_bytes: 16 * 1024 * 1024 * 1024,
1057 retained_attempt_limit: 8,
1058 }
1059 }
1060}
1061
1062#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1064#[serde(rename_all = "lowercase")]
1065pub enum MergeMode {
1066 None,
1069 Local,
1072 Pr,
1076}
1077
1078#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
1092#[serde(rename_all = "lowercase")]
1093pub enum MergeStyle {
1094 #[default]
1099 Merge,
1100 Squash,
1106 Rebase,
1112}
1113
1114#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1116#[serde(rename_all = "lowercase")]
1117pub enum MergeCi {
1118 #[default]
1120 Expected,
1121 None,
1123}
1124
1125impl MergeCi {
1126 pub fn expectation(self) -> crate::land::CiExpectation {
1128 match self {
1129 Self::Expected => crate::land::CiExpectation::Expected,
1130 Self::None => crate::land::CiExpectation::Absent,
1131 }
1132 }
1133}
1134
1135#[derive(Debug, Clone, Deserialize, Serialize)]
1137#[serde(deny_unknown_fields, default)]
1138pub struct Merge {
1139 pub mode: MergeMode,
1142 pub ci: MergeCi,
1144 pub base: Option<String>,
1146 pub style: MergeStyle,
1149 pub remote: String,
1151 pub release_bump: bool,
1164}
1165
1166impl Default for Merge {
1167 fn default() -> Self {
1168 Self {
1169 mode: MergeMode::None,
1170 ci: MergeCi::Expected,
1171 base: None,
1172 style: MergeStyle::default(),
1173 remote: "origin".to_owned(),
1174 release_bump: true,
1175 }
1176 }
1177}
1178
1179#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1181#[serde(rename_all = "lowercase")]
1182pub enum UpdateMode {
1183 Off,
1185 Notify,
1188 Install,
1190}
1191
1192#[derive(Debug, Clone, Deserialize, Serialize)]
1194#[serde(deny_unknown_fields, default)]
1195pub struct Update {
1196 pub mode: UpdateMode,
1198 pub interval: Option<String>,
1200 pub auto_restart: bool,
1202}
1203
1204impl Default for Update {
1205 fn default() -> Self {
1206 Self {
1207 mode: UpdateMode::Notify,
1208 interval: None,
1209 auto_restart: false,
1210 }
1211 }
1212}
1213
1214#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
1216#[serde(rename_all = "lowercase")]
1217pub enum ReleaseMode {
1218 #[default]
1221 Actions,
1222 Local,
1227}
1228
1229#[derive(Debug, Clone, Deserialize, Serialize)]
1231#[serde(deny_unknown_fields, default)]
1232pub struct Release {
1233 pub mode: ReleaseMode,
1236 pub commands: Vec<String>,
1243 pub timeout_minutes: u64,
1245 pub version_files: Vec<VersionFile>,
1253}
1254
1255#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1257#[serde(rename_all = "lowercase")]
1258pub enum VersionKind {
1259 Cargo,
1261 Json,
1263}
1264
1265#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
1267#[serde(deny_unknown_fields)]
1268pub struct VersionFile {
1269 pub path: String,
1271 pub kind: VersionKind,
1273}
1274
1275impl Default for Release {
1276 fn default() -> Self {
1277 Self {
1278 mode: ReleaseMode::Actions,
1279 commands: Vec::new(),
1280 timeout_minutes: 30,
1281 version_files: Vec::new(),
1282 }
1283 }
1284}
1285
1286impl Release {
1287 pub fn validate(&self) -> Result<()> {
1289 crate::release_manifest::validate(&self.version_files).context("[release] version_files")
1290 }
1291
1292 pub fn is_local(&self) -> bool {
1294 self.mode == ReleaseMode::Local
1295 }
1296}
1297
1298#[derive(Debug, Clone, Deserialize, Serialize)]
1300#[serde(try_from = "CoordinationFields")]
1301pub struct Coordination {
1302 pub contract_file: String,
1304 pub contract_token: String,
1306 pub lock_file: String,
1308}
1309
1310#[derive(Deserialize, Default)]
1311#[serde(deny_unknown_fields, default)]
1312struct CoordinationFields {
1313 contract_file: String,
1314 contract_token: String,
1315 lock_file: String,
1316}
1317
1318impl TryFrom<CoordinationFields> for Coordination {
1319 type Error = anyhow::Error;
1320
1321 fn try_from(fields: CoordinationFields) -> Result<Self> {
1322 for (key, name) in [
1323 ("coordination.contract_file", &fields.contract_file),
1324 ("coordination.lock_file", &fields.lock_file),
1325 ] {
1326 if name.trim().is_empty()
1327 || name != name.trim()
1328 || name == "."
1329 || name.contains("..")
1330 || name.contains(['/', '\\', ':', '\0'])
1331 {
1332 bail!(
1333 "{key} must be a plain file name inside the Git common directory (no separators or '..')"
1334 );
1335 }
1336 }
1337 let token = &fields.contract_token;
1338 if token.is_empty() || token.trim() != token || token.chars().any(char::is_control) {
1339 bail!(
1340 "coordination.contract_token must be a nonempty single-line token without surrounding whitespace"
1341 );
1342 }
1343 Ok(Self {
1344 contract_file: fields.contract_file,
1345 contract_token: fields.contract_token,
1346 lock_file: fields.lock_file,
1347 })
1348 }
1349}
1350
1351#[cfg(test)]
1352pub(crate) fn test_coordination() -> Option<Coordination> {
1353 Some(Coordination {
1354 contract_file: "updater.contract".into(),
1355 contract_token: "test-protocol-v1".into(),
1356 lock_file: "updater.lock".into(),
1357 })
1358}
1359
1360#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1362#[serde(deny_unknown_fields, default)]
1363pub struct Config {
1364 pub coordination: Option<Coordination>,
1366 pub agents: Vec<AgentSpec>,
1368 pub roles: Roles,
1370 pub graph: Graph,
1372 pub blind: Blind,
1374 pub verify: Verify,
1376 pub worktree: Worktree,
1378 pub disk: Disk,
1380 pub merge: Merge,
1382 pub update: Update,
1384 pub prompts: Prompts,
1386 pub notify: Notify,
1388 pub repos: Repos,
1391 pub talk: Talk,
1393 pub daemon: Daemon,
1395 pub release: Release,
1397 pub context_windows: BTreeMap<String, u64>,
1400}
1401
1402const BUILTIN_CONTEXT_WINDOWS: &[(&str, u64)] = &[
1412 ("claude-opus-4", 200_000),
1413 ("claude-sonnet-4", 200_000),
1414 ("claude-haiku-4", 200_000),
1415 ("claude-3", 200_000),
1416 ("opus", 200_000),
1417 ("sonnet", 200_000),
1418 ("haiku", 200_000),
1419 ("gpt-5", 400_000),
1420 ("gpt-4.1", 1_000_000),
1421 ("gpt-4o", 128_000),
1422 ("o3", 200_000),
1423 ("o4-mini", 200_000),
1424 ("gemini-2.5", 1_000_000),
1425 ("deepseek", 128_000),
1426];
1427
1428impl Config {
1429 pub fn context_window(&self, model: &str) -> Option<u64> {
1434 fn lookup<'a>(model: &str, entries: impl Iterator<Item = (&'a str, u64)>) -> Option<u64> {
1435 let mut best: Option<(usize, u64)> = None;
1436 for (key, window) in entries {
1437 if key == model {
1438 return Some(window);
1439 }
1440 if model.starts_with(key) && best.is_none_or(|(len, _)| key.len() > len) {
1441 best = Some((key.len(), window));
1442 }
1443 }
1444 best.map(|(_, w)| w)
1445 }
1446 lookup(
1447 model,
1448 self.context_windows.iter().map(|(k, w)| (k.as_str(), *w)),
1449 )
1450 .or_else(|| lookup(model, BUILTIN_CONTEXT_WINDOWS.iter().copied()))
1451 }
1452}
1453
1454#[derive(Debug, Clone, Deserialize, Serialize)]
1464#[serde(deny_unknown_fields, default)]
1465pub struct Daemon {
1466 pub max_concurrent_runs: usize,
1487 pub pause_for_interrupts: bool,
1503 pub max_deputies: usize,
1510 pub release_stall_minutes: u64,
1517}
1518
1519impl Default for Daemon {
1520 fn default() -> Self {
1521 Self {
1522 max_concurrent_runs: 1,
1523 pause_for_interrupts: false,
1524 max_deputies: 2,
1525 release_stall_minutes: 60,
1526 }
1527 }
1528}
1529
1530#[derive(Debug, Clone, Deserialize, Serialize)]
1542#[serde(deny_unknown_fields, default)]
1543pub struct Repos {
1544 pub roots: Vec<PathBuf>,
1548 pub auto_clone: bool,
1550 pub clone_command: Option<Vec<String>>,
1554 pub scan_ttl: u64,
1561 pub fetch_interval: u64,
1566}
1567
1568impl Default for Repos {
1569 fn default() -> Self {
1570 Self {
1571 roots: Vec::new(),
1572 auto_clone: false,
1573 clone_command: None,
1574 scan_ttl: 86_400,
1575 fetch_interval: 600,
1576 }
1577 }
1578}
1579
1580#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1596#[serde(deny_unknown_fields, default)]
1597pub struct Prompts {
1598 pub all: String,
1600 pub implement: String,
1602 pub judge: String,
1604 pub review: String,
1606 pub fix: String,
1608}
1609
1610impl Prompts {
1611 pub fn overlay(&self, node: &str) -> Option<String> {
1616 let specific = match node {
1617 "implement" => &self.implement,
1618 "judge" | "vote" | "deliberate" => &self.judge,
1619 "review" => &self.review,
1620 "fix" => &self.fix,
1621 _ => "",
1622 };
1623 let mut parts: Vec<&str> = Vec::new();
1624 for p in [self.all.trim(), specific.trim()] {
1625 if !p.is_empty() {
1626 parts.push(p);
1627 }
1628 }
1629 if parts.is_empty() {
1630 return None;
1631 }
1632 Some(parts.join("\n\n"))
1633 }
1634}
1635
1636#[derive(Debug, Clone, Default, Deserialize, Serialize)]
1643#[serde(deny_unknown_fields, default)]
1644pub struct Notify {
1645 pub command: Vec<String>,
1648}
1649
1650#[derive(Debug, Clone, Deserialize, Serialize)]
1652#[serde(deny_unknown_fields, default)]
1653pub struct Talk {
1654 pub allow_write: bool,
1663 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1665 pub standing_authorization: bool,
1666 pub completion_chat: bool,
1671 pub personas: Vec<PersonaSpec>,
1676 pub operator_name: Option<String>,
1680}
1681
1682pub const OPERATOR_NAME_MAX: usize = 64;
1684
1685impl Default for Talk {
1686 fn default() -> Self {
1687 Self {
1688 allow_write: false,
1689 standing_authorization: false,
1690 completion_chat: true,
1691 personas: Vec::new(),
1692 operator_name: None,
1693 }
1694 }
1695}
1696
1697impl Talk {
1698 pub fn operator_name(&self) -> Option<&str> {
1700 self.operator_name
1701 .as_deref()
1702 .map(str::trim)
1703 .filter(|n| !n.is_empty())
1704 }
1705}
1706
1707#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
1709#[serde(deny_unknown_fields)]
1710pub struct PersonaSpec {
1711 pub id: String,
1713 #[serde(default)]
1716 pub name: String,
1717 #[serde(default)]
1720 pub prompt: String,
1721 #[serde(default, skip_serializing_if = "Option::is_none")]
1725 pub icon: Option<String>,
1726}
1727
1728#[derive(Debug, Clone)]
1730pub struct ResolvedRoles {
1731 pub implementers: Vec<AgentSpec>,
1733 pub judges: Vec<AgentSpec>,
1735 pub reviewers: Vec<AgentSpec>,
1737 pub fixer: Option<Vec<AgentSpec>>,
1742 pub conductor: AgentSpec,
1744 pub implementer_roster: Vec<AgentSpec>,
1752 pub judge_roster: Vec<AgentSpec>,
1756 pub reviewer_roster: Vec<AgentSpec>,
1758}
1759
1760fn array_keys(table: &toml::value::Table, prefix: &str) -> Vec<String> {
1767 let mut out = Vec::new();
1768 for (k, v) in table {
1769 if prefix.is_empty() && k == "vars" {
1770 continue;
1771 }
1772 let path = if prefix.is_empty() {
1773 k.clone()
1774 } else {
1775 format!("{prefix}.{k}")
1776 };
1777 match v {
1778 toml::Value::Array(_) => out.push(path),
1779 toml::Value::Table(t) => out.extend(array_keys(t, &path)),
1780 _ => {}
1781 }
1782 }
1783 out
1784}
1785
1786#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1788enum ArrayMerge {
1789 Append,
1793 Replace,
1796}
1797
1798fn array_merge_policy(key: &str) -> ArrayMerge {
1837 match key {
1838 "verify.e2e" | "verify.gate" | "verify.pre_gate" | "repos.roots" => ArrayMerge::Append,
1839 _ => ArrayMerge::Replace,
1840 }
1841}
1842
1843impl Config {
1844 pub fn load(path: &Path) -> Result<Self> {
1847 Self::load_layers(&[path.to_path_buf()])
1848 }
1849
1850 fn render_ctx(paths: &[PathBuf]) -> teravars::Context {
1860 let mut ctx = teravars::system_context();
1861 let env: std::collections::BTreeMap<String, String> = std::env::vars().collect();
1862 ctx.insert("env", &env);
1863 if let Some(last) = paths.last()
1864 && let Some(dir) = last.parent()
1865 {
1866 let dir = std::fs::read_to_string(dir.join(REPO_MARKER))
1869 .map(|s| PathBuf::from(s.trim()))
1870 .unwrap_or_else(|_| dir.to_path_buf());
1871 ctx.insert("repo", &dir.to_string_lossy());
1872 ctx.insert(
1873 "repo_name",
1874 &dir.file_name().unwrap_or_default().to_string_lossy(),
1875 );
1876 }
1877 ctx
1878 }
1879
1880 pub fn load_layers(paths: &[PathBuf]) -> Result<Self> {
1888 Self::load_layers_with_machine(paths, Self::machine_layer())
1889 }
1890
1891 fn load_layers_with_machine(paths: &[PathBuf], machine: Option<PathBuf>) -> Result<Self> {
1892 let mut engine = teravars::Engine::default();
1893 let ctx = Self::render_ctx(paths);
1894 if paths.len() > 1 {
1895 Self::refuse_split_arrays(paths, &mut engine, &ctx).map_err(|error| {
1896 if error.downcast_ref::<ConfigFailure>().is_some() {
1897 error
1898 } else {
1899 let message = error.to_string();
1902 error
1903 .context(ConfigFailure::layers("config-merge", paths))
1904 .context(message)
1905 }
1906 })?;
1907 }
1908 let merged = teravars::load_merged(paths, &mut engine, &ctx)
1909 .map_err(|error| {
1910 let cause = ConfigFailure::render(&error, paths);
1911 anyhow::Error::new(error).context(cause)
1912 })
1913 .with_context(|| {
1914 format!(
1915 "rendering config via teravars: {}",
1916 paths
1917 .iter()
1918 .map(|p| p.display().to_string())
1919 .collect::<Vec<_>>()
1920 .join(", ")
1921 )
1922 })?;
1923 let mut table = merged.config;
1924 Self::normalize_renamed_keys(paths, &mut engine, &ctx, &mut table)?;
1925 let standing = table
1928 .get_mut("talk")
1929 .and_then(toml::Value::as_table_mut)
1930 .and_then(|talk| talk.remove("standing_authorization"));
1931 let standing = if standing.is_some()
1932 && let Some(machine) = machine.filter(|machine| paths.contains(machine))
1933 {
1934 let machine_paths = [machine];
1935 let mut engine = teravars::Engine::default();
1936 let layer = teravars::load_merged(
1937 &machine_paths,
1938 &mut engine,
1939 &Self::render_ctx(&machine_paths),
1940 )
1941 .context("read machine standing authorization")?;
1942 layer
1943 .config
1944 .get("talk")
1945 .and_then(|talk| talk.get("standing_authorization"))
1946 .map(|value| {
1947 value.as_bool().context(
1948 "[talk] standing_authorization in the machine layer must be a boolean",
1949 )
1950 })
1951 .transpose()?
1952 .unwrap_or(false)
1953 } else {
1954 false
1955 };
1956 table.remove("vars");
1959 let detect_agents = !table.contains_key("agents");
1963 let mut cfg: Self = toml::Value::Table(table)
1964 .try_into()
1965 .context("deserializing magi config")
1966 .context(ConfigFailure::layers("config-deserialize", paths))?;
1967 cfg.talk.standing_authorization = standing;
1968 if !cfg.graph.question_routing {
1969 tracing::warn!(
1970 "[graph] question_routing is retired and ignored; task inquiries always use their chat"
1971 );
1972 }
1973 crate::persona::validate(&cfg.talk.personas)?;
1974 if let Some(own) = cfg.disk.reclaim_free_bytes
1975 && own < cfg.disk.min_free_bytes
1976 {
1977 tracing::warn!(
1978 "[disk] reclaim_free_bytes ({own}) is below min_free_bytes ({}); collection aims at min_free_bytes",
1979 cfg.disk.min_free_bytes
1980 );
1981 }
1982 cfg.worktree.validate()?;
1983 cfg.release.validate()?;
1984 if let Some(name) = cfg.talk.operator_name() {
1985 if name.chars().count() > OPERATOR_NAME_MAX || name.chars().any(char::is_control) {
1986 bail!(
1987 "[talk] operator_name must be one line of at most {OPERATOR_NAME_MAX} characters"
1988 );
1989 }
1990 }
1991 if detect_agents {
1992 cfg.agents = Self::autodetected().agents;
1993 }
1994 Ok(cfg)
1995 }
1996
1997 fn normalize_renamed_keys(
2005 paths: &[PathBuf],
2006 engine: &mut teravars::Engine,
2007 ctx: &teravars::Context,
2008 table: &mut toml::map::Map<String, toml::Value>,
2009 ) -> Result<()> {
2010 let both = matches!(
2011 table.get("graph"),
2012 Some(toml::Value::Table(g)) if g.contains_key("candidates") && g.contains_key("implementers")
2013 );
2014 if !both {
2015 return Ok(());
2016 }
2017 let mut winner: Option<toml::Value> = None;
2018 for path in paths {
2019 let one = teravars::load_merged([path], engine, ctx)
2020 .map_err(|error| {
2021 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
2022 anyhow::Error::new(error).context(cause)
2023 })
2024 .with_context(|| format!("rendering {}", path.display()))?;
2025 let Some(toml::Value::Table(g)) = one.config.get("graph") else {
2026 continue;
2027 };
2028 if g.contains_key("candidates") && g.contains_key("implementers") {
2029 bail!(
2030 "`[graph]` sets both `implementers` and its deprecated alias \n `candidates` in {}; keep only `implementers`.",
2031 path.display()
2032 );
2033 }
2034 if let Some(v) = g.get("implementers").or_else(|| g.get("candidates")) {
2035 winner = Some(v.clone());
2036 }
2037 }
2038 if let Some(toml::Value::Table(g)) = table.get_mut("graph") {
2039 g.remove("candidates");
2040 if let Some(v) = winner {
2041 g.insert("implementers".to_owned(), v);
2042 }
2043 }
2044 Ok(())
2045 }
2046
2047 fn refuse_split_arrays(
2071 paths: &[PathBuf],
2072 engine: &mut teravars::Engine,
2073 ctx: &teravars::Context,
2074 ) -> Result<()> {
2075 let mut seen: std::collections::BTreeMap<String, PathBuf> = Default::default();
2076 for path in paths {
2077 let one = teravars::load_merged([path], engine, ctx)
2078 .map_err(|error| {
2079 let cause = ConfigFailure::render(&error, std::slice::from_ref(path));
2080 anyhow::Error::new(error).context(cause)
2081 })
2082 .with_context(|| format!("rendering {}", path.display()))?;
2083 for key in array_keys(&one.config, "") {
2084 if array_merge_policy(&key) == ArrayMerge::Append {
2085 continue;
2086 }
2087 if let Some(first) = seen.get(&key) {
2088 bail!(
2089 "`{key}` is an array declared in two config layers:\n \
2090 {}\n {}\nteravars appends arrays when it merges, so \
2091 magi would run the concatenation of both - which is \
2092 not what either file says. Declare `{key}` in exactly \
2093 one of them.",
2094 first.display(),
2095 path.display()
2096 );
2097 }
2098 seen.insert(key, path.clone());
2099 }
2100 }
2101 Ok(())
2102 }
2103
2104 pub fn array_provenance(paths: &[PathBuf], key: &str) -> Vec<(PathBuf, Vec<String>)> {
2126 let mut engine = teravars::Engine::default();
2127 let ctx = Self::render_ctx(paths);
2128 let mut out = Vec::new();
2129 for path in paths {
2130 let Ok(one) = teravars::load_merged([path], &mut engine, &ctx) else {
2131 continue;
2132 };
2133 let mut cur = &one.config;
2134 let mut found = None;
2135 let parts: Vec<&str> = key.split('.').collect();
2136 for (i, part) in parts.iter().enumerate() {
2137 match cur.get(*part) {
2138 Some(toml::Value::Array(a)) if i == parts.len() - 1 => {
2139 found = Some(a);
2140 break;
2141 }
2142 Some(toml::Value::Table(t)) => cur = t,
2143 _ => break,
2144 }
2145 }
2146 let Some(values) = found else { continue };
2147 let strings: Vec<String> = values
2148 .iter()
2149 .filter_map(|v| v.as_str().map(str::to_owned))
2150 .collect();
2151 if !strings.is_empty() {
2152 out.push((path.clone(), strings));
2153 }
2154 }
2155 out
2156 }
2157
2158 pub(crate) fn layer_tables(paths: &[PathBuf]) -> Vec<(PathBuf, Result<toml::Table>)> {
2164 let mut engine = teravars::Engine::default();
2165 let ctx = Self::render_ctx(paths);
2166 paths
2167 .iter()
2168 .map(|path| {
2169 let one = teravars::load_merged([path], &mut engine, &ctx)
2170 .map(|m| m.config)
2171 .with_context(|| format!("rendering {}", path.display()));
2172 (path.clone(), one)
2173 })
2174 .collect()
2175 }
2176
2177 pub fn describe_composed(
2187 paths: &[PathBuf],
2188 commands: &[String],
2189 key: &str,
2190 empty: &str,
2191 ) -> String {
2192 if commands.is_empty() {
2193 return empty.to_owned();
2194 }
2195 let joined = commands.join(" && ");
2196 let provenance = Self::array_provenance(paths, key);
2197 if provenance.len() <= 1 {
2198 return joined;
2199 }
2200 let mut out = joined;
2201 for (path, cmds) in &provenance {
2202 out.push_str(&format!("\n [{}] {}", path.display(), cmds.join(" && ")));
2203 }
2204 out
2205 }
2206
2207 #[track_caller]
2214 pub fn discover(repo: &Path, explicit: Option<&Path>) -> Result<(Self, Vec<PathBuf>)> {
2215 #[cfg(test)]
2216 crate::web::request_cost::discovery();
2217 tracing::trace!(
2218 caller = %std::panic::Location::caller(),
2219 explicit = explicit.is_some(),
2220 "discovering configuration"
2221 );
2222 if let Some(p) = explicit {
2223 let paths = vec![p.to_path_buf()];
2224 return Ok((Self::load_layers(&paths)?, paths));
2225 }
2226 let paths = Self::layers_checked(repo)?;
2227 if paths.is_empty() {
2228 return Ok((Self::autodetected(), paths));
2229 }
2230 Ok((Self::load_layers(&paths)?, paths))
2231 }
2232
2233 pub async fn discover_fetched(
2236 repo: &Path,
2237 explicit: Option<&Path>,
2238 ) -> Result<(Self, Vec<PathBuf>)> {
2239 if explicit.is_none() && is_git_repo(repo) {
2240 let (remote, cfg_base) = probe_remote_base(repo);
2244 let base = crate::git::merge_base_branch(repo, &remote, cfg_base.as_deref())
2245 .await
2246 .with_context(|| ConfigFailure {
2247 stage: "config-base",
2248 target: remote.clone(),
2249 })?;
2250 let out = crate::git::fetch(repo, &remote, &base)
2251 .await
2252 .with_context(|| format!("fetching {remote}/{base} to read magi.toml"))
2253 .with_context(|| ConfigFailure {
2254 stage: "config-fetch",
2255 target: format!("{remote}/{base}"),
2256 })?;
2257 if !out.ok() {
2258 return Err(anyhow::anyhow!(
2259 "cannot read magi.toml: `git fetch {remote} {base}` failed ({}); refusing to use the local checkout's copy, which may be stale",
2260 out.stderr.lines().next().unwrap_or("").trim()
2261 )).context(ConfigFailure { stage: "config-fetch", target: format!("{remote}/{base}") });
2262 }
2263 if cfg_base.is_none() {
2264 crate::git::ensure_remote_head(repo, &remote, &base).await;
2265 }
2266 }
2267 Self::discover(repo, explicit).map_err(|error| {
2268 if error.downcast_ref::<ConfigFailure>().is_some() {
2269 error
2270 } else {
2271 error.context(ConfigFailure {
2272 stage: "config-load",
2273 target: explicit.unwrap_or(repo).to_string_lossy().into_owned(),
2274 })
2275 }
2276 })
2277 }
2278
2279 fn layers_checked(repo: &Path) -> Result<Vec<PathBuf>> {
2281 let mut paths: Vec<PathBuf> = Self::machine_layer()
2282 .into_iter()
2283 .filter(|p| p.is_file())
2284 .collect();
2285 paths.extend(Self::repo_layers(repo)?);
2286 Ok(paths)
2287 }
2288
2289 pub(crate) fn repo_layer_description(repo: &Path, path: &Path) -> String {
2291 let cached = path.ancestors().find(|p| p.join(REPO_MARKER).is_file());
2292 if let Some(root) = cached {
2293 let relative = path.strip_prefix(root).unwrap_or(path);
2294 let reference = resolve_remote_base(repo)
2295 .map(|(remote, base)| format!("{remote}/{base}"))
2296 .unwrap_or_else(|_| "remote base".to_owned());
2297 format!(
2298 "{} at {reference} (including its includes)",
2299 repo.join(relative).display()
2300 )
2301 } else {
2302 format!("{} (including its includes)", path.display())
2303 }
2304 }
2305
2306 pub(crate) fn repo_layers(repo: &Path) -> Result<Vec<PathBuf>> {
2309 match inspect_git_repo(repo) {
2310 RepoKind::NotGit => Ok(local_repo_layers(repo)),
2311 RepoKind::Found(dirs) => remote_layers_with_git(repo, Some(dirs)),
2312 RepoKind::Fallback => remote_layers_fallback(repo),
2313 }
2314 }
2315
2316 pub const CONFIG_DIR_ENV: &str = "MAGI_CONFIG_DIR";
2336
2337 pub fn layers(repo: &Path) -> Vec<PathBuf> {
2342 let mut paths = Vec::new();
2343 paths.extend(Self::machine_layer());
2344 paths.push(repo.join(".magi").join("config.toml"));
2345 paths.push(repo.join("magi.toml"));
2346 paths.retain(|p| p.is_file());
2347 paths
2348 }
2349
2350 #[cfg(test)]
2357 pub(crate) fn machine_layer() -> Option<PathBuf> {
2358 std::env::var(Self::CONFIG_DIR_ENV)
2359 .ok()
2360 .filter(|dir| !dir.trim().is_empty())
2361 .map(|dir| PathBuf::from(dir).join("magi").join("config.toml"))
2362 }
2363
2364 #[cfg(not(test))]
2366 pub(crate) fn machine_layer() -> Option<PathBuf> {
2367 match std::env::var(Self::CONFIG_DIR_ENV) {
2368 Ok(dir) if dir.trim().is_empty() => None,
2370 Ok(dir) => Some(PathBuf::from(dir).join("magi").join("config.toml")),
2371 Err(_) => dirs::config_dir().map(|dir| dir.join("magi").join("config.toml")),
2372 }
2373 }
2374
2375 pub fn autodetected() -> Self {
2377 let mut cfg = Self::default();
2378 for (kind, id, model) in [
2379 (AgentKind::Claude, "opus", Some("opus")),
2380 (AgentKind::Claude, "sonnet", Some("sonnet")),
2381 (AgentKind::Antigravity, "antigravity", None),
2382 (AgentKind::Opencode, "opencode", None),
2383 (AgentKind::Codex, "codex", None),
2384 (AgentKind::Omp, "omp", None),
2385 ] {
2386 if kind.program().is_some_and(which) && !cfg.agents.iter().any(|a| a.id == id) {
2387 cfg.agents.push(AgentSpec {
2388 id: id.to_owned(),
2389 kind,
2390 model: model.map(str::to_owned),
2391 command: Vec::new(),
2392 extra_args: Vec::new(),
2393 env: BTreeMap::new(),
2394 prompt_delivery: None,
2395 max_turn_secs: None,
2396 });
2397 }
2398 }
2399 cfg
2400 }
2401
2402 pub fn cache_dir(&self) -> Option<PathBuf> {
2405 self.verify.cache_dir()
2406 }
2407
2408 pub fn agent(&self, id: &str) -> Result<&AgentSpec> {
2410 self.agents
2411 .iter()
2412 .find(|a| a.id == id)
2413 .with_context(|| format!("no agent with id `{id}` in the roster"))
2414 }
2415
2416 fn rotate(&self, ids: &[String], count: usize, offset: usize) -> Result<Vec<AgentSpec>> {
2423 let mut out = Vec::with_capacity(count);
2424 for i in 0..count {
2425 let spec = if ids.is_empty() {
2426 self.agents[(i + offset) % self.agents.len()].clone()
2427 } else {
2428 self.agent(&ids[i % ids.len()])?.clone()
2429 };
2430 out.push(spec);
2431 }
2432 Ok(out)
2433 }
2434
2435 fn full_roster(&self, ids: &[String]) -> Result<Vec<AgentSpec>> {
2442 if ids.is_empty() {
2443 Ok(self.agents.clone())
2444 } else {
2445 ids.iter().map(|id| self.agent(id).cloned()).collect()
2446 }
2447 }
2448
2449 pub fn resolve_roles(&self) -> Result<ResolvedRoles> {
2456 if self.agents.is_empty() {
2457 bail!(
2458 "agent roster is empty: no agent CLI found on PATH and no \
2459 [[agents]] in the config. Run `magi init` to write a starter \
2460 magi.toml."
2461 );
2462 }
2463 let pinned = self
2464 .graph
2465 .selected_implementer
2466 .as_ref()
2467 .map(|id| self.agent(id).cloned())
2468 .transpose()?;
2469 Ok(ResolvedRoles {
2470 implementers: match &pinned {
2471 Some(agent) => vec![agent.clone()],
2472 None => self.rotate(&self.roles.implementers, self.graph.implementers, 0)?,
2473 },
2474 judges: self.rotate(&self.roles.judges, self.graph.judges, 1)?,
2475 reviewers: self.rotate(&self.roles.reviewers, self.graph.reviewers, 0)?,
2476 fixer: match self.roles.fixer.as_ref() {
2477 Some(choice) => Some(crate::agent::pick_chain(
2480 &self.agents,
2481 Some(choice),
2482 &|_| true,
2483 "fixer",
2484 )?),
2485 None => None,
2486 },
2487 conductor: match self.roles.conductor.as_ref().map(AgentChoice::ids) {
2492 Some(ids) if ids.len() == 1 => self.agent(ids[0])?.clone(),
2493 Some(ids) if !ids.is_empty() => ids
2496 .iter()
2497 .find_map(|id| self.agent(id).ok())
2498 .cloned()
2499 .with_context(|| {
2500 format!("[roles] conductor names no agent in the roster: {ids:?}")
2501 })?,
2502 _ => crate::agent::pick(&self.agents, None, &crate::agent::installed)
2507 .unwrap_or_else(|_| self.agents[0].clone()),
2508 },
2509 implementer_roster: match pinned {
2510 Some(agent) => vec![agent],
2511 None => self.full_roster(&self.roles.implementers)?,
2512 },
2513 judge_roster: self.full_roster(&self.roles.judges)?,
2514 reviewer_roster: self.full_roster(&self.roles.reviewers)?,
2515 })
2516 }
2517
2518 pub fn advisors(&self) -> Result<Vec<AgentSpec>> {
2540 if self.agents.is_empty() {
2541 bail!(
2542 "agent roster is empty: no agent CLI found on PATH and no \
2543 [[agents]] in the config. Run `magi init` to write a starter \
2544 magi.toml."
2545 );
2546 }
2547 if !self.roles.advisors.is_empty() {
2548 return self.rotate(&self.roles.advisors, self.graph.advisors, 0);
2549 }
2550 self.rotate(&self.roles.judges, self.graph.advisors, 1)
2551 }
2552
2553 pub fn advisor_roster(&self) -> Result<Vec<AgentSpec>> {
2557 if self.roles.advisors.is_empty() {
2558 self.full_roster(&self.roles.judges)
2559 } else {
2560 self.full_roster(&self.roles.advisors)
2561 }
2562 }
2563
2564 pub fn shell(&self) -> Vec<String> {
2566 if let Some(s) = &self.verify.shell {
2567 return s.clone();
2568 }
2569 if which("sh") {
2570 vec!["sh".to_owned(), "-c".to_owned()]
2571 } else {
2572 vec!["cmd".to_owned(), "/C".to_owned()]
2573 }
2574 }
2575
2576 pub fn starter_toml() -> String {
2578 let detected = Self::autodetected();
2579 let mut s = String::from(
2580 "# magi — blind multi-agent implementation competition.\n\
2581 # `magi run \"<task>\"` walks: implement (N parallel worktrees)\n\
2582 # -> blind judging -> deliberation -> private final vote\n\
2583 # -> fold losers -> review + E2E loop -> gate -> merge.\n\
2584 #\n\
2585 # Rendered by teravars: a `[vars]` table, env\n\
2586 # and system lookups, and `include = [...]` all work. Tera\n\
2587 # braces are live everywhere in this file, but comments are\n\
2588 # stripped before rendering (teravars >= 0.2.2), so a comment\n\
2589 # may quote `{{ ... }}` freely.\n\
2590 #\n\
2591 # Layers deep-merge in increasing\n\
2592 # precedence, so the roster can live once per machine in\n\
2593 # <config_dir>/magi/config.toml and each repo only states its own\n\
2594 # gate:\n\
2595 # <config_dir>/magi/config.toml < .magi/config.toml < magi.toml\n\n\
2596 [vars]\n\
2597 # Reference it as vars.cache inside Tera braces, anywhere below.\n\
2598 # Single quotes inside the braces: teravars renders the raw file\n\
2599 # text, so TOML's own \\\" escaping never reaches Tera.\n\
2600 cache = \"{{ env.MAGI_CACHE | default(value='/tmp') }}\"\n\n",
2601 );
2602 if detected.agents.is_empty() {
2603 s.push_str(
2604 "# No agent CLI was found on PATH. Fill this in by hand.\n\
2605 # kind = claude | opencode | antigravity | codex | command\n\
2606 [[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n",
2607 );
2608 } else {
2609 for a in &detected.agents {
2610 s.push_str("[[agents]]\n");
2611 s.push_str(&format!("id = {:?}\n", a.id));
2612 s.push_str(&format!("kind = {:?}\n", a.kind.as_str()));
2613 if let Some(m) = &a.model {
2614 s.push_str(&format!("model = {m:?}\n"));
2615 }
2616 s.push('\n');
2617 }
2618 }
2619 s.push_str(
2620 "# Leave a role list empty to rotate through the roster.\n\
2621 # A non-empty list is also an ordered backup list: seats take entries from the\n\
2622 # front (see [graph] counts) and a failed or out-of-quota seat moves on to the\n\
2623 # next agent to its right, each tried once. Same for judges and reviewers.\n\
2624 # implementers = [\"opus\", \"codex\", \"sonnet\"] # with implementers = 1 below: opus sits, codex then sonnet are spares\n\
2625 [roles]\n\
2626 implementers = []\n\
2627 judges = []\n\
2628 reviewers = []\n\
2629 # conductor = \"opus\" # arranges the queue; unset picks a seat like chatter does\n\
2630 # synthesizer = \"opus\" # blends the advisors into one brief; unset picks a seat like chatter does\n\
2631 # synthesizer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\
2632 # language_judge = \"jev\" # kind = \"command\" wrapper deciding if PR text is English; unset keeps the built-in heuristics\n\
2633 # dupes_judge = \"opus\" # judges duplicate-work claims; unset inherits chatter (string or fallback chain)\n\
2634 # fixer = \"opus\" # applies review findings; unset keeps the winner's own author\n\
2635 # fixer = [\"opus\", \"codex\"] # array form: fallback chain, each tried once on quota or failure\n\n\
2636 [graph]\n\
2637 # Gate GitHub prose; secret redaction is always enabled.\n\
2638 github_text_guard = true\n\
2639 # Language of PR / issue titles, bodies and comments; non-English drops the English-only check (commits stay English).\n\
2640 github_language = \"en\"\n\
2641 implementers = 3\n\
2642 judges = 3\n\
2643 deliberate_rounds = 1\n\
2644 reviewers = 3\n\
2645 review_rounds = 6\n\
2646 # Fix rounds a failing verify.gate gets before the run is blocked (0 = none).\n\
2647 gate_fix_rounds = 1\n\
2648 # Rerun a failed required CI check once before a land fix round (flaky tests).\n\
2649 rerun_flaky_checks = true\n\
2650 # 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\
2651 rerun_failed_e2e = true\n\
2652 # Port the strengths judges named in the losing candidates onto the\n\
2653 # winner before review (best-effort; rolled back on failure or a big diff).\n\
2654 graft_runner_up = true\n\
2655 max_parallel = 4\n\
2656 language = \"en\"\n\
2657 # One CLI conversation per seat: judges keep their own argument\n\
2658 # across deliberation, the fixer keeps its implementation context.\n\
2659 sessions = true\n\
2660 # Reviewer-seat timeout. When timeout_verify is omitted, E2E and\n\
2661 # the final gate inherit this value for compatibility.\n\
2662 timeout_review = 1200\n\
2663 # Optional independent E2E/final-gate timeout; uncomment to keep\n\
2664 # verification independent if timeout_review changes later.\n\
2665 # timeout_verify = 1200\n\
2666 # Longest a seat waits for the shared build cache before it is\n\
2667 # spawned. Never counted against an agent's own timeout; expiry\n\
2668 # holds the run (resumable) instead of failing the agent.\n\
2669 # timeout_resource_wait = 1800\n\n\
2670 # What the chat calls you (persona address and the Chat's turn label).\n\
2671 # [talk]\n\
2672 # standing_authorization = false # machine layer only; bounded chat recovery\n\
2673 # completion_chat = true # report human/issue-filed task completion to its task chat\n\
2674 # operator_name = \"Commander\"\n\n\
2675 # Chat personas (tone only; the web Chat picks one per conversation).\n\
2676 # Built in: magi, rei, misato, ritsuko, shinji, asuka, kaworu. Entries add to\n\
2677 # them, and one with a built-in's id replaces it. `default` is the plain\n\
2678 # voice and cannot be redefined (it may only set `icon`). Declare this in one\n\
2679 # layer only. `icon` is an optional avatar, display only: an absolute or\n\
2680 # ~/ path to a png/jpg/gif/webp, or a data:image/...;base64 URI, up to\n\
2681 # 256 KiB; a missing or bad one falls back to the built-in avatar.\n\
2682 # [[talk.personas]]\n\
2683 # id = \"gendo\"\n\
2684 # name = \"Gendo Ikari\"\n\
2685 # prompt = \"Speak coldly and tersely, hands folded.\"\n\
2686 # icon = \"~/pictures/gendo.png\"\n\n\
2687 [verify]\n\
2688 # Run once per review round in the winner's worktree; failures are\n\
2689 # fed back to the fixer.\n\
2690 e2e = []\n\
2691 # Final gate. Every command must exit 0 before a merge.\n\
2692 gate = []\n\
2693 # Mechanical fixers (formatters) run in the winner's worktree before\n\
2694 # e2e and before the gate; whatever they change becomes one commit. A\n\
2695 # failing command only warns - the gate stays the arbiter. Same timeout\n\
2696 # as the gate (timeout_verify). Keep it light and idempotent.\n\
2697 # pre_gate = []\n\n\
2698 # Prepare each worktree magi creates (candidates, judges, advisors,\n\
2699 # reviewers, the operator-fix and review-takeover checkouts), in order,\n\
2700 # before any agent or verify command touches it. `copy` reads from the\n\
2701 # primary checkout and never overwrites; `optional` skips a missing\n\
2702 # source. `run` goes through the shell with the worktree as cwd and\n\
2703 # fails the seat on a non-zero exit or timeout (timeout_secs, default\n\
2704 # the verify timeout). Setup must not edit tracked files, and what it\n\
2705 # leaves untracked is kept out of magi's commits. Declare this in one\n\
2706 # layer only.\n\
2707 # [worktree]\n\
2708 # setup = [\n\
2709 # { copy = \".env.example -> .env\" },\n\
2710 # { copy = \".env.local\", optional = true },\n\
2711 # { run = \"pnpm install --frozen-lockfile\", timeout_secs = 900 },\n\
2712 # ]\n\
2713 # pre_clean = [] # Repeatable cleanup before owned clean -fdx.\n\n\
2714 [merge]\n\
2715 # none | local | pr\n\
2716 mode = \"none\"\n\
2717 # expected (default) | none. Set none only in repository config without CI.\n\
2718 # Ignores all check statuses; reviews and approval still apply.\n\
2719 # ci = \"expected\"\n\
2720 # release_bump = true # Rust (Cargo.toml) repositories only; a no-op elsewhere\n\n\
2721 [update]\n\
2722 # off | notify | install — checked in the background, throttled.\n\
2723 mode = \"notify\"\n\
2724 # interval = \"24h\"\n\n\
2725 # Opt-in: magi web updates and restarts automatically when a newer release is found.\n\
2726 # auto_restart = false\n\
2727 # Uses interval above; off / MAGI_NO_AUTOUPDATE disable it.\n\
2728 # Handover drains only short admission transactions; active workers continue\n\
2729 # on their original executable generation while new work uses the new one.\n\
2730 # Standalone magi serve cannot restart.\n\
2731 # Failed tags are skipped until process restart or a different tag.\n\
2732 # Older binaries reject auto_restart: upgrade before adding the key.\n\n\
2733 [daemon]\n\
2734 # Minutes a release-bump pull request (chore/release-v*) may sit with\n\
2735 # no new commit and no check changing state before `magi serve`\n\
2736 # notices and asks you. A failed check is rerun once on its own;\n\
2737 # still red after that escalates at once. 0 turns the watcher off.\n\
2738 # release_stall_minutes = 60\n\n\
2739 [release]\n\
2740 # actions (default) | local. \"local\" is for repositories whose GitHub\n\
2741 # Actions never run (private, no minutes): the release pull request\n\
2742 # does not wait for CI, you approve the merge in magi, and then\n\
2743 # `magi serve` pushes the vX.Y.Z tag (never over an existing one) and\n\
2744 # runs `commands` from a clean checkout of the merge commit. A\n\
2745 # failure holds the release with a notice; it is never retried blind.\n\
2746 # Needs `magi serve` running and [daemon] release_stall_minutes > 0.\n\
2747 # For ordinary pull requests without CI, also set [merge] ci = \"none\".\n\
2748 # mode = \"actions\"\n\
2749 # Run in order; the first failure stops. They see MAGI_RELEASE_VERSION,\n\
2750 # MAGI_RELEASE_TAG, MAGI_RELEASE_COMMIT and MAGI_RELEASE_PR. Make them\n\
2751 # safe to repeat: a crash mid-command is treated as unfinished.\n\
2752 # commands = [\"cargo build --release\", \"gh release create \\\"$MAGI_RELEASE_TAG\\\" --generate-notes\"]\n\
2753 # timeout_minutes = 30\n\
2754 # Repositories whose Cargo.toml is not at the root (e.g. a Tauri app).\n\
2755 # The first entry is the version of record and must be the file the\n\
2756 # repository's auto-tag.yml reads (kind \"cargo\"); the others are\n\
2757 # rewritten to the same version. Paths are relative to the repository\n\
2758 # root. Cargo.lock beside the first entry follows; package-lock.json\n\
2759 # is not touched.\n\
2760 # version_files = [\n\
2761 # { path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n\
2762 # { path = \"package.json\", kind = \"json\" },\n\
2763 # { path = \"src-tauri/tauri.conf.json\", kind = \"json\" },\n\
2764 # ]\n",
2765 );
2766 s
2767 }
2768}
2769
2770pub fn which(program: &str) -> bool {
2772 find_program(program).is_some()
2773}
2774
2775pub fn find_program(program: &str) -> Option<PathBuf> {
2784 find_program_on(program, &std::env::var_os("PATH")?)
2785}
2786
2787pub fn find_program_on(program: &str, paths: &std::ffi::OsStr) -> Option<PathBuf> {
2790 let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".EXE;.CMD;.BAT".into());
2791 find_program_in(program, paths, cfg!(windows).then_some(pathext.as_str()))
2792}
2793
2794fn find_program_in(
2795 program: &str,
2796 paths: &std::ffi::OsStr,
2797 pathext: Option<&str>,
2798) -> Option<PathBuf> {
2799 let p = Path::new(program);
2800 if p.components().count() > 1 {
2801 return p.is_file().then(|| p.to_path_buf());
2802 }
2803 std::env::split_paths(paths).find_map(|dir| match pathext {
2804 Some(exts) => {
2805 let bare = dir.join(program);
2806 if p.extension().is_some() && bare.is_file() {
2807 return Some(bare);
2808 }
2809 exts.split(';')
2810 .filter(|e| !e.is_empty())
2811 .map(|e| dir.join(format!("{program}{}", e.to_lowercase())))
2812 .find(|c| c.is_file())
2813 }
2814 None => Some(dir.join(program)).filter(|c| c.is_file()),
2815 })
2816}
2817
2818const REPO_MARKER: &str = ".magi-repo";
2820
2821const CACHE_MANIFEST: &str = ".magi-cache-manifest.json";
2824const CACHE_MANIFEST_VERSION: u32 = 3;
2825const REPO_LAYER_RELS: [&str; 2] = [".magi/config.toml", "magi.toml"];
2826
2827const GIT_OVERRIDE_ENVS: &[&str] = &[
2831 "GIT_DIR",
2832 "GIT_COMMON_DIR",
2833 "GIT_WORK_TREE",
2834 "GIT_OBJECT_DIRECTORY",
2835 "GIT_ALTERNATE_OBJECT_DIRECTORIES",
2836 "GIT_CEILING_DIRECTORIES",
2837 "GIT_DISCOVERY_ACROSS_FILESYSTEM",
2838 "GIT_NAMESPACE",
2839];
2840
2841fn has_git_env_override() -> bool {
2842 GIT_OVERRIDE_ENVS
2843 .iter()
2844 .any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty()))
2845}
2846
2847#[derive(Debug, Clone)]
2848struct GitDirs {
2849 common_dir: PathBuf,
2850 files_ref_backend: bool,
2851}
2852
2853#[derive(Debug, Clone)]
2854enum RepoKind {
2855 NotGit,
2856 Found(GitDirs),
2857 Fallback,
2858}
2859
2860fn local_repo_layers(repo: &Path) -> Vec<PathBuf> {
2861 [
2862 repo.join(".magi").join("config.toml"),
2863 repo.join("magi.toml"),
2864 ]
2865 .into_iter()
2866 .filter(|p| p.is_file())
2867 .collect()
2868}
2869
2870fn inspect_git_repo(repo: &Path) -> RepoKind {
2871 if has_git_env_override() || !repo.is_dir() {
2872 return RepoKind::Fallback;
2873 }
2874 let start = match repo.canonicalize() {
2875 Ok(p) => p,
2876 Err(_) => {
2877 if repo.is_absolute() {
2878 repo.to_path_buf()
2879 } else {
2880 match std::env::current_dir() {
2881 Ok(cwd) => cwd.join(repo),
2882 Err(_) => return RepoKind::Fallback,
2883 }
2884 }
2885 }
2886 };
2887
2888 for dir in start.ancestors() {
2889 let dot_git = dir.join(".git");
2890 match std::fs::symlink_metadata(&dot_git) {
2891 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
2892 if dir.join("HEAD").is_file()
2895 && dir.join("objects").is_dir()
2896 && (dir.join("refs").is_dir() || dir.join("reftable").is_dir())
2897 {
2898 return RepoKind::Fallback;
2899 }
2900 continue;
2901 }
2902 Err(_) => return RepoKind::Fallback,
2903 Ok(meta) => {
2904 if meta.file_type().is_symlink() {
2905 return RepoKind::Fallback;
2906 }
2907 let git_dir = if meta.is_dir() {
2908 if !dot_git.join("HEAD").is_file() {
2909 return RepoKind::Fallback;
2910 }
2911 dot_git
2912 } else if meta.is_file() {
2913 let Ok(raw) = std::fs::read_to_string(&dot_git) else {
2914 return RepoKind::Fallback;
2915 };
2916 let Some(target) = raw
2917 .trim_end_matches(['\r', '\n'])
2918 .strip_prefix("gitdir:")
2919 .map(str::trim)
2920 .filter(|s| !s.is_empty())
2921 else {
2922 return RepoKind::Fallback;
2923 };
2924 let target_path = PathBuf::from(target);
2925 let resolved = if target_path.is_absolute() {
2926 target_path
2927 } else {
2928 dir.join(target_path)
2929 };
2930 if !resolved.is_dir() || !resolved.join("HEAD").is_file() {
2931 return RepoKind::Fallback;
2932 }
2933 resolved
2934 } else {
2935 return RepoKind::Fallback;
2936 };
2937
2938 let commondir_file = git_dir.join("commondir");
2939 let common_dir = match std::fs::symlink_metadata(&commondir_file) {
2940 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
2941 git_dir.canonicalize().unwrap_or(git_dir)
2942 }
2943 Ok(m) if m.is_file() => {
2944 let Ok(raw) = std::fs::read_to_string(&commondir_file) else {
2945 return RepoKind::Fallback;
2946 };
2947 let target = raw.trim();
2948 if target.is_empty() {
2949 return RepoKind::Fallback;
2950 }
2951 let target_path = PathBuf::from(target);
2952 let joined = if target_path.is_absolute() {
2953 target_path
2954 } else {
2955 git_dir.join(target_path)
2956 };
2957 let Ok(canonical) = joined.canonicalize() else {
2958 return RepoKind::Fallback;
2959 };
2960 if !canonical.is_dir() {
2961 return RepoKind::Fallback;
2962 }
2963 canonical
2964 }
2965 _ => return RepoKind::Fallback,
2966 };
2967
2968 let files_ref_backend = is_standard_files_ref_backend(&common_dir);
2969 return RepoKind::Found(GitDirs {
2970 common_dir,
2971 files_ref_backend,
2972 });
2973 }
2974 }
2975 }
2976 RepoKind::NotGit
2977}
2978
2979fn is_git_repo(repo: &Path) -> bool {
2980 match inspect_git_repo(repo) {
2981 RepoKind::NotGit => false,
2982 RepoKind::Found(_) => true,
2983 RepoKind::Fallback => is_git_worktree(repo),
2984 }
2985}
2986
2987fn strip_git_config_value(raw: &str) -> String {
2988 let mut out = String::new();
2989 let mut in_quotes = false;
2990 let mut escaped = false;
2991 for ch in raw.chars() {
2992 if escaped {
2993 out.push(ch);
2994 escaped = false;
2995 continue;
2996 }
2997 if in_quotes {
2998 match ch {
2999 '\\' => escaped = true,
3000 '"' => in_quotes = false,
3001 _ => out.push(ch),
3002 }
3003 continue;
3004 }
3005 match ch {
3006 '"' => in_quotes = true,
3007 '#' | ';' => break,
3008 _ => out.push(ch),
3009 }
3010 }
3011 out.trim().to_owned()
3012}
3013
3014fn is_standard_files_ref_backend(common_dir: &Path) -> bool {
3018 if common_dir.join("reftable").exists() || !common_dir.join("refs").is_dir() {
3019 return false;
3020 }
3021 let Ok(config) = std::fs::read_to_string(common_dir.join("config")) else {
3022 return false;
3023 };
3024 let mut section = String::new();
3025 for raw_line in config.lines() {
3026 let line = raw_line.trim();
3027 if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
3028 continue;
3029 }
3030 if line.ends_with('\\') {
3031 return false;
3032 }
3033 if let Some(rest) = line.strip_prefix('[') {
3034 let Some(end) = rest.find(']') else {
3035 return false;
3036 };
3037 let trailing = rest[end + 1..].trim();
3038 if !trailing.is_empty() && !trailing.starts_with('#') && !trailing.starts_with(';') {
3039 return false;
3040 }
3041 let header = &rest[..end];
3042 section = header
3043 .split(|c: char| c.is_ascii_whitespace() || c == '"')
3044 .next()
3045 .unwrap_or("")
3046 .to_ascii_lowercase();
3047 if matches!(section.as_str(), "include" | "includeif") {
3048 return false;
3049 }
3050 continue;
3051 }
3052 let (key, val) = match line.split_once('=') {
3053 Some((k, v)) => (
3054 k.trim().to_ascii_lowercase(),
3055 strip_git_config_value(v).to_ascii_lowercase(),
3056 ),
3057 None => (
3058 strip_git_config_value(line).to_ascii_lowercase(),
3059 "true".to_owned(),
3060 ),
3061 };
3062 match section.as_str() {
3063 "core" if key == "repositoryformatversion" => {
3064 if !matches!(val.as_str(), "0" | "1") {
3065 return false;
3066 }
3067 }
3068 "extensions" => match key.as_str() {
3069 "refstorage" if val == "files" => {}
3070 "objectformat" if val == "sha1" => {}
3071 "worktreeconfig" | "relativeworktrees" | "partialclone" | "promisor"
3072 | "preciousobjects" | "noop" | "manyfiles" => {}
3073 _ => return false,
3074 },
3075 _ => {}
3076 }
3077 }
3078 true
3079}
3080
3081fn is_safe_ref_name(name: &str) -> bool {
3082 if !name.starts_with("refs/")
3083 || name.ends_with('/')
3084 || name.starts_with("refs/bisect/")
3085 || name.starts_with("refs/worktree/")
3086 || name.starts_with("refs/rewritten/")
3087 {
3088 return false;
3089 }
3090 name.split('/').all(|part| {
3091 !part.is_empty()
3092 && part != "."
3093 && part != ".."
3094 && !part.contains('\\')
3095 && !part.bytes().any(|b| b <= 0x20 || b == 0x7f)
3096 })
3097}
3098
3099fn join_rel_path(base: &Path, rel: &str) -> PathBuf {
3100 let mut path = base.to_path_buf();
3101 for part in rel.split('/') {
3102 path.push(part);
3103 }
3104 path
3105}
3106
3107fn is_sha1_hex(s: &str) -> bool {
3108 s.len() == 40 && s.bytes().all(|b| b.is_ascii_hexdigit())
3109}
3110
3111fn is_hex_oid(s: &str) -> bool {
3112 (s.len() == 40 || s.len() == 64) && s.bytes().all(|b| b.is_ascii_hexdigit())
3113}
3114
3115enum LooseRef {
3116 Missing,
3117 Oid(String),
3118 Symref(String),
3119 Unknown,
3120}
3121
3122fn read_loose_ref(common_dir: &Path, ref_name: &str) -> LooseRef {
3123 if !is_safe_ref_name(ref_name) {
3124 return LooseRef::Unknown;
3125 }
3126 let path = join_rel_path(common_dir, ref_name);
3127 match std::fs::symlink_metadata(&path) {
3128 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return LooseRef::Missing,
3129 Err(_) => return LooseRef::Unknown,
3130 Ok(meta) if !meta.is_file() => return LooseRef::Unknown,
3131 Ok(_) => {}
3132 }
3133 match std::fs::read_to_string(&path) {
3134 Err(e) if e.kind() == std::io::ErrorKind::NotFound => LooseRef::Missing,
3135 Err(_) => LooseRef::Unknown,
3136 Ok(raw) => {
3137 let trimmed = raw.trim();
3138 if let Some(target) = trimmed.strip_prefix("ref:") {
3139 let target = target.trim();
3140 if is_safe_ref_name(target) {
3141 LooseRef::Symref(target.to_owned())
3142 } else {
3143 LooseRef::Unknown
3144 }
3145 } else if is_sha1_hex(trimmed) {
3146 LooseRef::Oid(trimmed.to_ascii_lowercase())
3147 } else {
3148 LooseRef::Unknown
3149 }
3150 }
3151 }
3152}
3153
3154enum PackedRef {
3155 Missing,
3156 Oid(String),
3157 Unknown,
3158}
3159
3160fn read_packed_ref(common_dir: &Path, ref_name: &str) -> PackedRef {
3161 let raw = match std::fs::read_to_string(common_dir.join("packed-refs")) {
3162 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return PackedRef::Missing,
3163 Err(_) => return PackedRef::Unknown,
3164 Ok(raw) => raw,
3165 };
3166 let mut lines = raw.lines().peekable();
3167 while let Some(line) = lines.next() {
3168 let line = line.trim_end_matches('\r');
3169 if line.is_empty() || line.starts_with('#') || line.starts_with('^') {
3170 continue;
3171 }
3172 let Some((oid, name)) = line.split_once(' ') else {
3173 return PackedRef::Unknown;
3174 };
3175 if name == ref_name {
3176 if !is_sha1_hex(oid) {
3177 return PackedRef::Unknown;
3178 }
3179 if lines
3180 .peek()
3181 .is_some_and(|next| next.trim_end_matches('\r').starts_with('^'))
3182 {
3183 return PackedRef::Unknown;
3185 }
3186 return PackedRef::Oid(oid.to_ascii_lowercase());
3187 }
3188 }
3189 PackedRef::Missing
3190}
3191
3192fn resolve_remote_head_files(common_dir: &Path, remote: &str) -> Option<String> {
3193 let head = format!("refs/remotes/{remote}/HEAD");
3194 match read_loose_ref(common_dir, &head) {
3195 LooseRef::Symref(target) => crate::git::remote_head_branch(remote, &target),
3196 _ => None,
3197 }
3198}
3199
3200fn resolve_ref_oid_files(common_dir: &Path, start_ref: &str) -> Option<String> {
3201 let mut current = start_ref.to_owned();
3202 for _ in 0..8 {
3203 match read_loose_ref(common_dir, ¤t) {
3204 LooseRef::Oid(oid) => return Some(oid),
3205 LooseRef::Symref(next) => current = next,
3206 LooseRef::Missing => {
3207 return match read_packed_ref(common_dir, ¤t) {
3208 PackedRef::Oid(oid) => Some(oid),
3209 PackedRef::Missing | PackedRef::Unknown => None,
3210 };
3211 }
3212 LooseRef::Unknown => return None,
3213 }
3214 }
3215 None
3216}
3217
3218fn repository_git() -> std::process::Command {
3219 #[cfg(test)]
3220 crate::web::request_cost::git();
3221 let mut command = std::process::Command::new("git");
3222 command.arg("--no-replace-objects");
3223 command
3224}
3225
3226fn git_out(repo: &Path, args: &[&str]) -> Option<String> {
3227 use crate::proc::Quiet as _;
3228 let out = repository_git()
3229 .args(args)
3230 .quiet()
3231 .current_dir(repo)
3232 .stdin(std::process::Stdio::null())
3233 .output()
3234 .ok()?;
3235 out.status
3236 .success()
3237 .then(|| String::from_utf8_lossy(&out.stdout).into_owned())
3238}
3239
3240fn is_git_worktree(repo: &Path) -> bool {
3243 git_out(repo, &["rev-parse", "--git-dir"]).is_some()
3244}
3245
3246#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3249pub enum OwnerHold {
3250 LandApproval,
3252 HoldContestedMerge,
3254}
3255
3256impl OwnerHold {
3257 pub const ALL: [Self; 2] = [Self::LandApproval, Self::HoldContestedMerge];
3259
3260 pub fn key(self) -> &'static str {
3262 match self {
3263 Self::LandApproval => "land_approval",
3264 Self::HoldContestedMerge => "hold_contested_merge",
3265 }
3266 }
3267
3268 pub fn base_value(self, graph: &Graph) -> bool {
3270 match self {
3271 Self::LandApproval => graph.land_approval,
3272 Self::HoldContestedMerge => graph.hold_contested_merge,
3273 }
3274 }
3275}
3276
3277pub async fn branch_owner_holds(
3280 repo: &Path,
3281 head: &str,
3282) -> (Vec<(OwnerHold, String)>, Vec<String>) {
3283 let mut holds = Vec::new();
3284 let mut diagnostics = Vec::new();
3285 if let Err(error) =
3288 crate::git::git(repo, &["cat-file", "-e", &format!("{head}^{{commit}}")]).await
3289 {
3290 diagnostics.push(format!("cannot read reviewed commit {head}: {error:#}"));
3291 return (holds, diagnostics);
3292 }
3293 for file in ["magi.toml", ".magi/config.toml"] {
3294 let object = format!("{head}:{file}");
3295 let text = match crate::git::git(repo, &["show", &object]).await {
3296 Ok(text) => text,
3297 Err(error) => {
3298 let error = format!("{error:#}");
3300 if !error.contains("does not exist in")
3301 && !error.contains("exists on disk, but not in")
3302 {
3303 diagnostics.push(format!(
3304 "cannot read reviewed branch {file} at {head}: {error}"
3305 ));
3306 }
3307 continue;
3308 }
3309 };
3310 let value = match toml::from_str::<toml::Value>(&text) {
3311 Ok(value) => value,
3312 Err(error) => {
3313 diagnostics.push(format!(
3314 "cannot parse reviewed branch {file} at {head}: {error}"
3315 ));
3316 continue;
3317 }
3318 };
3319 if value.get("include").is_some() || text.contains("{{") || text.contains("{%") {
3320 diagnostics.push(format!("reviewed branch {file} at {head}: only literal owner holds are read; includes and templates are ignored"));
3321 }
3322 for hold in OwnerHold::ALL {
3323 if value
3324 .get("graph")
3325 .and_then(|g| g.get(hold.key()))
3326 .and_then(toml::Value::as_bool)
3327 == Some(true)
3328 {
3329 holds.push((hold, file.to_owned()));
3330 }
3331 }
3332 }
3333 (holds, diagnostics)
3334}
3335
3336#[derive(Deserialize, Default)]
3337struct ProbeMerge {
3338 base: Option<String>,
3339 remote: Option<String>,
3340}
3341
3342#[derive(Deserialize, Default)]
3343struct Probe {
3344 merge: Option<ProbeMerge>,
3345}
3346
3347fn probe_merge(path: &Path, repo: &Path) -> Option<ProbeMerge> {
3353 if !path.is_file() {
3354 return None;
3355 }
3356 let paths = [path.to_path_buf()];
3357 let mut engine = teravars::Engine::default();
3358 let mut ctx = Config::render_ctx(&paths);
3359 ctx.insert("repo", &repo.to_string_lossy());
3362 ctx.insert(
3363 "repo_name",
3364 &repo.file_name().unwrap_or_default().to_string_lossy(),
3365 );
3366 if let Ok(merged) = teravars::load_merged(&paths, &mut engine, &ctx)
3367 && let Ok(probe) = toml::Value::Table(merged.config).try_into::<Probe>()
3368 {
3369 return probe.merge;
3370 }
3371 let text = std::fs::read_to_string(path).ok()?;
3372 toml::from_str::<Probe>(&text).ok()?.merge
3373}
3374
3375fn probe_remote_base(repo: &Path) -> (String, Option<String>) {
3377 let mut remote = None;
3378 let mut base = None;
3379 let mut sources: Vec<PathBuf> = Config::machine_layer().into_iter().collect();
3380 sources.push(repo.join("magi.toml"));
3381 sources.push(repo.join(".magi").join("config.toml"));
3382 for path in sources {
3383 if let Some(m) = probe_merge(&path, repo) {
3384 remote = remote.or(m.remote.filter(|s| !s.trim().is_empty()));
3385 base = base.or(m.base.filter(|s| !s.trim().is_empty()));
3386 }
3387 }
3388 (remote.unwrap_or_else(|| "origin".to_owned()), base)
3389}
3390
3391fn resolve_remote_base(repo: &Path) -> Result<(String, String)> {
3393 let (remote, base) = probe_remote_base(repo);
3394 let base = match base {
3395 Some(b) => b,
3396 None => {
3397 let from_files = match inspect_git_repo(repo) {
3398 RepoKind::Found(dirs) if dirs.files_ref_backend => {
3399 resolve_remote_head_files(&dirs.common_dir, &remote)
3400 }
3401 _ => None,
3402 };
3403 match from_files {
3404 Some(b) => b,
3405 None => {
3406 let head = format!("refs/remotes/{remote}/HEAD");
3407 git_out(repo, &["symbolic-ref", "--quiet", &head])
3408 .and_then(|s| crate::git::remote_head_branch(&remote, &s))
3409 .with_context(|| missing_remote_head_msg(&remote))?
3410 }
3411 }
3412 }
3413 };
3414 Ok((remote, base))
3415}
3416
3417fn missing_remote_head_msg(remote: &str) -> String {
3418 format!(
3419 "cannot tell which branch of `{remote}` holds magi.toml: \
3420 set [merge] base, or run `git remote set-head {remote} -a`"
3421 )
3422}
3423
3424fn missing_tracking_ref_msg(remote: &str, base: &str) -> String {
3425 format!(
3426 "`{remote}/{base}` does not exist in this checkout; fetch it \
3427 (`git fetch {remote} {base}`) or set [merge] base/remote. magi will not read \
3428 a possibly stale local magi.toml instead"
3429 )
3430}
3431
3432fn fnv_hex(text: &str) -> String {
3433 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
3434 for b in text.bytes() {
3435 hash ^= u64::from(b);
3436 hash = hash.wrapping_mul(0x0100_0000_01b3);
3437 }
3438 format!("{hash:016x}")
3439}
3440
3441fn declares_include(text: &str) -> bool {
3447 match toml::from_str::<toml::Table>(text) {
3448 Ok(table) => {
3449 table.contains_key("include")
3450 || table
3451 .get("teravars")
3452 .and_then(toml::Value::as_table)
3453 .is_some_and(|t| t.contains_key("include"))
3454 }
3455 Err(_) => text.contains("include"),
3456 }
3457}
3458
3459fn extract_tree(repo: &Path, sha: &str, dest: &Path) -> Result<()> {
3462 use crate::proc::Quiet as _;
3463 let mut archive = repository_git()
3464 .args(["archive", "--format=tar", sha])
3465 .quiet()
3466 .current_dir(repo)
3467 .stdin(std::process::Stdio::null())
3468 .stdout(std::process::Stdio::piped())
3469 .stderr(std::process::Stdio::null())
3470 .spawn()
3471 .context("running git archive")?;
3472 let tar = std::process::Command::new("tar")
3473 .arg("-x")
3474 .arg("-C")
3475 .arg(dest)
3476 .quiet()
3477 .stdin(archive.stdout.take().context("git archive has no stdout")?)
3478 .output()
3479 .context("running tar")?;
3480 let status = archive.wait().context("waiting for git archive")?;
3481 if !status.success() || !tar.status.success() {
3482 bail!(
3483 "cannot unpack {sha} for the config's includes: {}",
3484 String::from_utf8_lossy(&tar.stderr).trim()
3485 );
3486 }
3487 Ok(())
3488}
3489
3490fn write_extracted(path: &Path, bytes: impl AsRef<[u8]>) -> Result<()> {
3491 use std::io::Write as _;
3492 match std::fs::remove_file(path) {
3493 Ok(()) => {}
3494 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
3495 Err(e) => return Err(e.into()),
3496 }
3497 std::fs::File::create_new(path)?.write_all(bytes.as_ref())?;
3498 Ok(())
3499}
3500
3501#[derive(Debug, Serialize, Deserialize)]
3502struct CacheManifest {
3503 version: u32,
3504 sha: String,
3505 repo: String,
3506 layers: Vec<String>,
3507 extracted_tree: bool,
3508}
3509
3510fn read_cached_layers(dir: &Path, sha: &str, repo: &Path) -> Option<Vec<PathBuf>> {
3511 let raw = std::fs::read(dir.join(CACHE_MANIFEST)).ok()?;
3512 let manifest: CacheManifest = serde_json::from_slice(&raw).ok()?;
3513 if manifest.version != CACHE_MANIFEST_VERSION
3514 || manifest.sha != sha
3515 || manifest.repo != repo.to_string_lossy()
3516 || manifest.layers.len() > REPO_LAYER_RELS.len()
3517 {
3518 return None;
3519 }
3520 let mut out = Vec::with_capacity(manifest.layers.len());
3521 let mut last_idx: Option<usize> = None;
3522 for rel in &manifest.layers {
3523 let idx = REPO_LAYER_RELS.iter().position(|allowed| *allowed == rel)?;
3524 if last_idx.is_some_and(|prev| idx <= prev) {
3525 return None;
3526 }
3527 last_idx = Some(idx);
3528 let file = join_rel_path(dir, rel);
3529 if !file.is_file() || !file.parent().is_some_and(|p| p.join(REPO_MARKER).is_file()) {
3530 return None;
3531 }
3532 out.push(file);
3533 }
3534 Some(out)
3535}
3536
3537enum BatchEntry {
3538 Missing,
3539 Object {
3540 oid: String,
3541 kind: String,
3542 content: Vec<u8>,
3543 },
3544}
3545
3546fn parse_cat_file_batch(mut buf: &[u8], expected: usize) -> Result<Vec<BatchEntry>> {
3547 let mut entries = Vec::with_capacity(expected);
3548 for _ in 0..expected {
3549 let Some(nl) = buf.iter().position(|&b| b == b'\n') else {
3550 bail!("unexpected EOF in git cat-file --batch header");
3551 };
3552 let line = std::str::from_utf8(&buf[..nl])
3553 .context("non-UTF-8 git cat-file --batch header")?
3554 .trim_end_matches('\r');
3555 buf = &buf[nl + 1..];
3556 if line.ends_with(" missing") || line.ends_with(" ambiguous") {
3557 entries.push(BatchEntry::Missing);
3558 continue;
3559 }
3560 let mut parts = line.split_whitespace();
3561 let (Some(oid), Some(kind), Some(size_str), None) =
3562 (parts.next(), parts.next(), parts.next(), parts.next())
3563 else {
3564 bail!("unexpected git cat-file --batch header: {line}");
3565 };
3566 let size: usize = size_str
3567 .parse()
3568 .with_context(|| format!("invalid git cat-file --batch size: {size_str}"))?;
3569 if buf.len() < size + 1 || buf[size] != b'\n' {
3570 bail!("truncated git cat-file --batch body for {oid}");
3571 }
3572 let content = buf[..size].to_vec();
3573 buf = &buf[size + 1..];
3574 entries.push(BatchEntry::Object {
3575 oid: oid.to_owned(),
3576 kind: kind.to_owned(),
3577 content,
3578 });
3579 }
3580 Ok(entries)
3581}
3582
3583fn read_commit_layers_batch(
3586 repo: &Path,
3587 sha: &str,
3588 remote: &str,
3589 base: &str,
3590) -> Result<(String, Vec<(&'static str, String)>)> {
3591 use crate::proc::Quiet as _;
3592 use std::io::Write as _;
3593
3594 let mut child = repository_git()
3595 .args(["cat-file", "--batch"])
3596 .quiet()
3597 .current_dir(repo)
3598 .stdin(std::process::Stdio::piped())
3599 .stdout(std::process::Stdio::piped())
3600 .stderr(std::process::Stdio::piped())
3601 .spawn()
3602 .context("running git cat-file --batch")?;
3603 if let Some(mut stdin) = child.stdin.take() {
3604 let mut query = format!("{sha}^{{commit}}\n");
3605 for rel in REPO_LAYER_RELS {
3606 query.push_str(&format!("{sha}:{rel}\n"));
3607 }
3608 if let Err(e) = stdin.write_all(query.as_bytes())
3609 && e.kind() != std::io::ErrorKind::BrokenPipe
3610 {
3611 return Err(e).context("writing query to git cat-file --batch");
3612 }
3613 }
3614 let out = child
3615 .wait_with_output()
3616 .context("waiting for git cat-file --batch")?;
3617 if !out.status.success() {
3618 bail!(
3619 "cannot read config from {remote}/{base} ({sha}): {}",
3620 String::from_utf8_lossy(&out.stderr).trim()
3621 );
3622 }
3623 let entries = parse_cat_file_batch(&out.stdout, 1 + REPO_LAYER_RELS.len())?;
3624 let mut iter = entries.into_iter();
3625 let commit_sha = match iter.next() {
3626 Some(BatchEntry::Object { oid, kind, .. }) if kind == "commit" && is_hex_oid(&oid) => oid,
3627 _ => bail!("{}", missing_tracking_ref_msg(remote, base)),
3628 };
3629 let present_paths = if iter
3632 .as_slice()
3633 .iter()
3634 .any(|e| matches!(e, BatchEntry::Missing))
3635 {
3636 let tree = git_out(
3637 repo,
3638 &[
3639 "ls-tree",
3640 "--full-tree",
3641 "--name-only",
3642 &commit_sha,
3643 "--",
3644 ".magi/config.toml",
3645 "magi.toml",
3646 ],
3647 )
3648 .context("cannot read repository configuration tree")?;
3649 tree.lines().map(str::to_owned).collect::<Vec<_>>()
3650 } else {
3651 Vec::new()
3652 };
3653 let mut texts = Vec::new();
3654 for (rel, entry) in REPO_LAYER_RELS.into_iter().zip(iter) {
3655 match entry {
3656 BatchEntry::Missing => {
3657 if present_paths.iter().any(|path| path == rel) {
3658 bail!("cannot read {rel} from {remote}/{base} ({commit_sha}): missing object");
3659 }
3660 }
3661 BatchEntry::Object { kind, content, .. } if kind == "blob" => {
3662 texts.push((rel, String::from_utf8_lossy(&content).into_owned()));
3663 }
3664 BatchEntry::Object { kind, .. } => {
3665 bail!(
3666 "cannot read {rel} from {remote}/{base} ({commit_sha}): expected blob, found {kind}"
3667 );
3668 }
3669 }
3670 }
3671 Ok((commit_sha, texts))
3672}
3673
3674fn resolve_common_and_commit_cli(
3675 repo: &Path,
3676 remote: &str,
3677 base: &str,
3678) -> Option<(PathBuf, String)> {
3679 let spec = format!("refs/remotes/{remote}/{base}^{{commit}}");
3680 if !remote.starts_with('-') && !base.starts_with('-') {
3681 let out = git_out(
3682 repo,
3683 &[
3684 "rev-parse",
3685 "--path-format=absolute",
3686 "--git-common-dir",
3687 &spec,
3688 ],
3689 )?;
3690 let mut lines = out.lines().map(str::trim).filter(|l| !l.is_empty());
3691 let common = lines.next()?;
3692 let sha = lines.next()?;
3693 if lines.next().is_none() && is_hex_oid(sha) {
3694 return Some((PathBuf::from(common), sha.to_owned()));
3695 }
3696 }
3697 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
3698 .map(|s| s.trim().to_owned())
3699 .filter(|s| is_hex_oid(s))?;
3700 let common = git_out(
3701 repo,
3702 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
3703 )
3704 .map(|s| PathBuf::from(s.trim()))?;
3705 Some((common, sha))
3706}
3707
3708fn resolve_remote_head_and_commit_cli(repo: &Path, remote: &str) -> Result<(String, String)> {
3712 let head = format!("refs/remotes/{remote}/HEAD");
3713 if let Some(out) = git_out(
3714 repo,
3715 &[
3716 "for-each-ref",
3717 "--format=%(refname)%09%(symref)%09%(objecttype)%09%(objectname)%09%(*objecttype)%09%(*objectname)",
3718 &head,
3719 ],
3720 ) {
3721 for line in out.lines() {
3722 let parts: Vec<&str> = line.trim_end_matches('\r').split('\t').collect();
3723 if parts.len() != 6 || parts[0] != head {
3724 continue;
3725 }
3726 let symref = parts[1];
3727 if let Some(base) = crate::git::remote_head_branch(remote, symref) {
3728 if parts[2] == "commit" && is_hex_oid(parts[3]) {
3729 return Ok((base, parts[3].to_owned()));
3730 }
3731 if parts[4] == "commit" && is_hex_oid(parts[5]) {
3732 return Ok((base, parts[5].to_owned()));
3733 }
3734 let spec = format!("refs/remotes/{remote}/{base}^{{commit}}");
3735 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
3736 .map(|s| s.trim().to_owned())
3737 .filter(|s| is_hex_oid(s))
3738 .with_context(|| missing_tracking_ref_msg(remote, &base))?;
3739 return Ok((base, sha));
3740 }
3741 }
3742 }
3743 let base = git_out(repo, &["symbolic-ref", "--quiet", &head])
3746 .and_then(|s| crate::git::remote_head_branch(remote, &s))
3747 .with_context(|| missing_remote_head_msg(remote))?;
3748 let spec = format!("refs/remotes/{remote}/{base}^{{commit}}");
3749 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
3750 .map(|s| s.trim().to_owned())
3751 .filter(|s| is_hex_oid(s))
3752 .with_context(|| missing_tracking_ref_msg(remote, &base))?;
3753 Ok((base, sha))
3754}
3755
3756fn remote_layers_fallback(repo: &Path) -> Result<Vec<PathBuf>> {
3757 let (remote, cfg_base) = probe_remote_base(repo);
3758 if let Some(base) = cfg_base {
3759 if let Some((common_dir, sha)) = resolve_common_and_commit_cli(repo, &remote, &base) {
3760 return materialize_remote_layers(repo, Some(common_dir), &remote, &base, &sha, true);
3761 }
3762 if !is_git_worktree(repo) {
3763 return Ok(local_repo_layers(repo));
3764 }
3765 bail!("{}", missing_tracking_ref_msg(&remote, &base));
3766 }
3767 if !is_git_worktree(repo) {
3768 return Ok(local_repo_layers(repo));
3769 }
3770 remote_layers_with_git(repo, None)
3771}
3772
3773fn remote_layers_with_git(repo: &Path, git_dirs: Option<GitDirs>) -> Result<Vec<PathBuf>> {
3776 let (remote, cfg_base) = probe_remote_base(repo);
3777
3778 if let Some(dirs) = &git_dirs
3782 && dirs.files_ref_backend
3783 {
3784 let base_from_files = match &cfg_base {
3785 Some(b) => Some(b.clone()),
3786 None => resolve_remote_head_files(&dirs.common_dir, &remote),
3787 };
3788 if let Some(base) = base_from_files {
3789 let tracking = format!("refs/remotes/{remote}/{base}");
3790 if let Some(sha) = resolve_ref_oid_files(&dirs.common_dir, &tracking) {
3791 return materialize_remote_layers(
3792 repo,
3793 Some(dirs.common_dir.clone()),
3794 &remote,
3795 &base,
3796 &sha,
3797 false,
3798 );
3799 }
3800 }
3801 }
3802
3803 let (common_dir, base, sha) = match (git_dirs, cfg_base) {
3807 (Some(dirs), Some(base)) => {
3808 let spec = format!("refs/remotes/{remote}/{base}^{{commit}}");
3809 let sha = git_out(repo, &["rev-parse", "--verify", "--quiet", &spec])
3810 .map(|s| s.trim().to_owned())
3811 .filter(|s| is_hex_oid(s))
3812 .with_context(|| missing_tracking_ref_msg(&remote, &base))?;
3813 (Some(dirs.common_dir), base, sha)
3814 }
3815 (Some(dirs), None) => {
3816 let (base, sha) = resolve_remote_head_and_commit_cli(repo, &remote)?;
3817 (Some(dirs.common_dir), base, sha)
3818 }
3819 (None, Some(base)) => {
3820 let (common_dir, sha) = resolve_common_and_commit_cli(repo, &remote, &base)
3821 .with_context(|| missing_tracking_ref_msg(&remote, &base))?;
3822 (Some(common_dir), base, sha)
3823 }
3824 (None, None) => {
3825 let (base, sha) = resolve_remote_head_and_commit_cli(repo, &remote)?;
3826 (None, base, sha)
3827 }
3828 };
3829 materialize_remote_layers(repo, common_dir, &remote, &base, &sha, true)
3830}
3831
3832fn materialize_remote_layers(
3833 repo: &Path,
3834 common_dir: Option<PathBuf>,
3835 remote: &str,
3836 base: &str,
3837 sha: &str,
3838 verified: bool,
3839) -> Result<Vec<PathBuf>> {
3840 let repo_key = repo.to_string_lossy();
3841 let key_for = |commit_sha: &str| {
3842 format!(
3843 "{commit_sha}-{}-v{CACHE_MANIFEST_VERSION}",
3844 fnv_hex(&repo_key)
3845 )
3846 };
3847 let primary_root = common_dir.map(|c| c.join("magi").join("config"));
3848 let fallback_root = dirs::cache_dir().map(|p| p.join("magi").join("config"));
3849 let lookup = |commit_sha: &str| -> Option<Vec<PathBuf>> {
3850 let key = key_for(commit_sha);
3851 if let Some(root) = &primary_root
3852 && let Some(layers) = read_cached_layers(&root.join(&key), commit_sha, repo)
3853 {
3854 return Some(layers);
3855 }
3856 read_cached_layers(&fallback_root.as_ref()?.join(&key), commit_sha, repo)
3857 };
3858 if let Some(layers) = lookup(sha) {
3859 if !verified {
3860 let commit = git_out(
3864 repo,
3865 &[
3866 "rev-parse",
3867 "--verify",
3868 "--quiet",
3869 &format!("{sha}^{{commit}}"),
3870 ],
3871 );
3872 if !commit.is_some_and(|s| s.trim() == sha) {
3873 bail!("{}", missing_tracking_ref_msg(remote, base));
3874 }
3875 }
3876 return Ok(layers);
3877 }
3878
3879 let (commit_sha, texts) = read_commit_layers_batch(repo, sha, remote, base)?;
3880 if commit_sha != sha
3881 && let Some(layers) = lookup(&commit_sha)
3882 {
3883 return Ok(layers);
3884 }
3885
3886 let key = key_for(&commit_sha);
3887 let wants_tree = texts.iter().any(|(_, t)| declares_include(t));
3888 let build = |root: &Path| -> Result<Vec<PathBuf>> {
3892 let final_dir = root.join(&key);
3893 if let Some(layers) = read_cached_layers(&final_dir, &commit_sha, repo) {
3894 return Ok(layers);
3895 }
3896 static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3897 let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3898 std::fs::create_dir_all(root)?;
3899 let tmp = root.join(format!(
3900 "{key}.tmp-{}-{}-{seq}",
3901 std::process::id(),
3902 std::time::SystemTime::now()
3903 .duration_since(std::time::UNIX_EPOCH)
3904 .map(|d| d.as_nanos())
3905 .unwrap_or_default()
3906 ));
3907 let filled = (|| -> Result<()> {
3908 std::fs::create_dir_all(&tmp)?;
3909 if wants_tree {
3910 extract_tree(repo, &commit_sha, &tmp)?;
3911 }
3912 for (rel, text) in &texts {
3913 let file = join_rel_path(&tmp, rel);
3914 let parent = file.parent().unwrap_or(&tmp);
3915 std::fs::create_dir_all(parent)?;
3916 write_extracted(&file, text)?;
3917 write_extracted(&parent.join(REPO_MARKER), repo.to_string_lossy().as_bytes())?;
3918 }
3919 let manifest = CacheManifest {
3920 version: CACHE_MANIFEST_VERSION,
3921 sha: commit_sha.clone(),
3922 repo: repo.to_string_lossy().into_owned(),
3923 layers: texts.iter().map(|(rel, _)| (*rel).to_owned()).collect(),
3924 extracted_tree: wants_tree,
3925 };
3926 write_extracted(
3927 &tmp.join(CACHE_MANIFEST),
3928 serde_json::to_vec(&manifest).context("serialize config cache manifest")?,
3929 )?;
3930 Ok(())
3931 })();
3932 if let Err(e) = filled {
3933 let _ = std::fs::remove_dir_all(&tmp);
3934 return Err(e);
3935 }
3936 if std::fs::rename(&tmp, &final_dir).is_err() {
3937 let _ = std::fs::remove_dir_all(&tmp);
3942 return read_cached_layers(&final_dir, &commit_sha, repo)
3943 .with_context(|| format!("cannot place {}", final_dir.display()));
3944 }
3945 Ok(texts
3946 .iter()
3947 .map(|(rel, _)| join_rel_path(&final_dir, rel))
3948 .collect())
3949 };
3950 let layers = match primary_root.as_deref().map(&build) {
3951 Some(Ok(layers)) => layers,
3952 _ => {
3953 let root = fallback_root
3954 .as_deref()
3955 .context("no user config cache directory")?;
3956 build(root).with_context(|| format!("extracting config from {remote}/{base}"))?
3957 }
3958 };
3959 Ok(layers)
3960}
3961
3962#[cfg(test)]
3963mod tests {
3964 #[test]
3965 fn standing_authorization_is_only_from_the_named_machine_layer() {
3966 let dir = tempfile::tempdir().unwrap();
3967 let machine = dir.path().join("machine.toml");
3968 let repo = dir.path().join("magi.toml");
3969 std::fs::write(&machine, "[talk]\nstanding_authorization = false\n").unwrap();
3970 std::fs::write(&repo, "[talk]\nstanding_authorization = true\n").unwrap();
3971 let layers = [machine.clone(), repo.clone()];
3972 let load = |paths| Config::load_layers_with_machine(paths, Some(machine.clone())).unwrap();
3973 assert!(!load(&layers).talk.standing_authorization);
3974 assert!(
3975 !load(std::slice::from_ref(&repo))
3976 .talk
3977 .standing_authorization
3978 );
3979 std::fs::write(&machine, "[talk]\nstanding_authorization = true\n").unwrap();
3980 std::fs::write(&repo, "[talk]\nstanding_authorization = false\n").unwrap();
3981 assert!(load(&layers).talk.standing_authorization);
3982 }
3983
3984 #[test]
3985 fn run_records_with_the_retired_editing_network_key_still_load() {
3986 for value in ["enabled", "restricted"] {
3988 let mut graph = serde_json::to_value(Graph::default()).unwrap();
3989 graph["editing_network"] = serde_json::json!(value);
3990 let back: Graph = serde_json::from_value(graph).unwrap();
3991 assert!(
3992 serde_json::to_value(&back)
3993 .unwrap()
3994 .get("editing_network")
3995 .is_none()
3996 );
3997 let from_toml: Graph = toml::from_str(&format!("editing_network = {value:?}")).unwrap();
3998 assert!(
3999 !toml::to_string(&from_toml)
4000 .unwrap()
4001 .contains("editing_network")
4002 );
4003 }
4004 }
4005
4006 #[test]
4007 fn coordination_defaults_off_and_validates_rendered_layer_values() {
4008 let dir = tempfile::tempdir().unwrap();
4009 let machine = dir.path().join("machine.toml");
4010 let repo = dir.path().join("repo.toml");
4011 std::fs::write(&machine, "").unwrap();
4012 assert!(Config::default().coordination.is_none());
4013 assert!(Config::load(&machine).unwrap().coordination.is_none());
4014 std::fs::write(
4015 &machine,
4016 r#"
4017[vars]
4018contract = "updater.contract"
4019[coordination]
4020contract_file = "{{ vars.contract }}"
4021contract_token = "protocol-v1"
4022lock_file = "updater.lock"
4023"#,
4024 )
4025 .unwrap();
4026 let cfg = Config::load(&machine).unwrap();
4027 let policy = cfg.coordination.unwrap();
4028 assert_eq!(policy.contract_file, "updater.contract");
4029 assert_eq!(policy.contract_token, "protocol-v1");
4030 assert_eq!(policy.lock_file, "updater.lock");
4031 std::fs::write(&repo, "[coordination]\nlock_file = 'repository.lock'\n").unwrap();
4032 let cfg = Config::load_layers(&[machine.clone(), repo.clone()]).unwrap();
4033 let policy = cfg.coordination.unwrap();
4034 assert_eq!(policy.contract_file, "updater.contract");
4035 assert_eq!(policy.lock_file, "repository.lock");
4036 std::fs::write(
4037 &repo,
4038 r#"
4039[vars]
4040bad = "../escape"
4041[coordination]
4042lock_file = "{{ vars.bad }}"
4043"#,
4044 )
4045 .unwrap();
4046 let error = Config::load_layers(&[machine, repo]).unwrap_err();
4047 assert!(format!("{error:#}").contains("coordination.lock_file"));
4048 }
4049
4050 #[test]
4051 fn coordination_rejects_invalid_names_tokens_and_incomplete_sections() {
4052 let dir = tempfile::tempdir().unwrap();
4053 let path = dir.path().join("config.toml");
4054 let valid = toml::toml! {
4055 [coordination]
4056 contract_file = "updater.contract"
4057 contract_token = "protocol-v1"
4058 lock_file = "updater.lock"
4059 };
4060 for key in ["contract_file", "lock_file"] {
4061 for bad in [
4062 "",
4063 " ",
4064 " file",
4065 "file ",
4066 "\tfile",
4067 "file\t",
4068 ".",
4069 "..",
4070 "file..name",
4071 "../escape",
4072 "a/b",
4073 "a\\b",
4074 "/absolute",
4075 "C:drive",
4076 "C:\\absolute",
4077 "nul\0name",
4078 ] {
4079 let mut table = valid.clone();
4080 table["coordination"][key] = bad.into();
4081 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
4082 let error = Config::load(&path).unwrap_err();
4083 assert!(
4084 format!("{error:#}").contains(&format!("coordination.{key}")),
4085 "{bad:?}: {error:#}"
4086 );
4087 }
4088 }
4089 for bad in ["", " ", " token", "token ", "two\nlines", "two\rlines"] {
4090 let mut table = valid.clone();
4091 table["coordination"]["contract_token"] = bad.into();
4092 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
4093 let error = Config::load(&path).unwrap_err();
4094 assert!(
4095 format!("{error:#}").contains("coordination.contract_token"),
4096 "{error:#}"
4097 );
4098 }
4099 for key in ["contract_file", "contract_token", "lock_file"] {
4100 let mut table = valid.clone();
4101 table["coordination"].as_table_mut().unwrap().remove(key);
4102 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
4103 let error = Config::load(&path).unwrap_err();
4104 assert!(
4105 format!("{error:#}").contains(&format!("coordination.{key}")),
4106 "{error:#}"
4107 );
4108 }
4109 let mut table = valid;
4110 table["coordination"]
4111 .as_table_mut()
4112 .unwrap()
4113 .insert("typo".into(), "value".into());
4114 std::fs::write(&path, toml::to_string(&table).unwrap()).unwrap();
4115 assert!(format!("{:#}", Config::load(&path).unwrap_err()).contains("typo"));
4116 }
4117
4118 #[test]
4119 fn context_window_prefers_exact_then_longest_prefix_and_user_over_builtin() {
4120 let mut cfg = Config::default();
4121 assert_eq!(
4122 cfg.context_window("claude-sonnet-4-5-20250929"),
4123 Some(200_000)
4124 );
4125 assert_eq!(cfg.context_window("gpt-4.1-mini"), Some(1_000_000));
4126 assert_eq!(cfg.context_window("mystery-model"), None);
4127 cfg.context_windows
4128 .insert("claude-sonnet-4-5".into(), 1_000_000);
4129 cfg.context_windows.insert("claude-sonnet-4".into(), 5);
4130 cfg.context_windows.insert("mystery".into(), 32_768);
4131 assert_eq!(
4133 cfg.context_window("claude-sonnet-4-5-20250929"),
4134 Some(1_000_000)
4135 );
4136 cfg.context_windows
4138 .insert("claude-sonnet-4-5-20250929".into(), 7);
4139 assert_eq!(cfg.context_window("claude-sonnet-4-5-20250929"), Some(7));
4140 assert_eq!(cfg.context_window("mystery-model"), Some(32_768));
4141 }
4142
4143 use super::*;
4144
4145 #[test]
4148 fn windows_lookup_picks_the_cmd_shim_over_the_extensionless_script() {
4149 let dir = tempfile::tempdir().unwrap();
4150 std::fs::write(dir.path().join("codex"), "#!/bin/sh\n").unwrap();
4151 std::fs::write(dir.path().join("codex.cmd"), "@echo off\n").unwrap();
4152 let paths = dir.path().as_os_str();
4153 assert_eq!(
4154 find_program_in("codex", paths, Some(".EXE;.CMD")),
4155 Some(dir.path().join("codex.cmd"))
4156 );
4157 assert_eq!(
4158 find_program_in("codex", paths, None),
4159 Some(dir.path().join("codex"))
4160 );
4161 assert_eq!(find_program_in("claude", paths, Some(".EXE;.CMD")), None);
4162 }
4163
4164 fn spec(id: &str) -> AgentSpec {
4165 AgentSpec {
4166 id: id.to_owned(),
4167 kind: AgentKind::Command,
4168 model: None,
4169 command: vec!["true".to_owned()],
4170 extra_args: Vec::new(),
4171 env: BTreeMap::new(),
4172 prompt_delivery: None,
4173 max_turn_secs: None,
4174 }
4175 }
4176
4177 #[test]
4178 fn merge_ci_defaults_expected_and_requires_an_explicit_valid_opt_out() {
4179 let default: Merge = toml::from_str("").unwrap();
4180 assert_eq!(default.ci, MergeCi::Expected);
4181 let config = layered("", "[merge]\nci = \"none\"\n").unwrap();
4182 assert_eq!(
4183 config.merge.ci.expectation(),
4184 crate::land::CiExpectation::Absent
4185 );
4186 assert!(toml::from_str::<Merge>("ci = \"typo\"").is_err());
4187 assert!(Config::starter_toml().contains("# ci = \"expected\""));
4188 }
4189
4190 #[test]
4191 fn github_text_guard_defaults_on_and_can_be_disabled() {
4192 let default: Graph = toml::from_str("").unwrap();
4193 assert!(default.github_text_guard);
4194 let disabled: Graph = toml::from_str("github_text_guard = false").unwrap();
4195 assert!(!disabled.github_text_guard);
4196 let config = layered("", "[graph]\ngithub_text_guard = false\n").unwrap();
4197 assert!(!config.graph.github_text_guard);
4198 assert!(Config::starter_toml().contains("github_text_guard = true"));
4199 }
4200
4201 #[test]
4202 fn rerun_flaky_checks_defaults_on_and_is_in_the_starter() {
4203 assert!(Graph::default().rerun_flaky_checks);
4204 let off: Graph = toml::from_str("rerun_flaky_checks = false").unwrap();
4205 assert!(!off.rerun_flaky_checks);
4206 assert!(Config::starter_toml().contains("rerun_flaky_checks = true"));
4207 }
4208
4209 #[test]
4210 fn timeout_verify_omitted_from_old_toml_inherits_timeout_review() {
4211 let g: Graph = toml::from_str("timeout_review = 3600").expect("parse");
4216 assert_eq!(g.timeout_verify, None);
4217 assert_eq!(g.verify_timeout(), 3600);
4218 }
4219
4220 #[test]
4221 fn shrinking_timeout_review_does_not_shrink_timeout_verify() {
4222 let g: Graph = toml::from_str("timeout_review = 45").expect("parse");
4227 assert_eq!(g.timeout_review, 45);
4228 assert_eq!(
4229 g.verify_timeout(),
4230 45,
4231 "an omitted legacy value follows review"
4232 );
4233 let explicit: Graph = toml::from_str("timeout_review = 45\ntimeout_verify = 1200")
4234 .expect("parse explicit override");
4235 assert_eq!(explicit.verify_timeout(), 1200);
4236 }
4237
4238 #[test]
4239 fn graph_implementers_new_key_loads_and_old_key_is_an_alias() {
4240 let g: Graph = toml::from_str("implementers = 4\n").unwrap();
4241 assert_eq!(g.implementers, 4);
4242 let g: Graph = toml::from_str("candidates = 5\n").unwrap();
4243 assert_eq!(g.implementers, 5);
4244 }
4245
4246 fn layered(lower: &str, upper: &str) -> Result<Config> {
4247 let dir = tempfile::tempdir().unwrap();
4248 let a = dir.path().join("a.toml");
4249 let b = dir.path().join("b.toml");
4250 std::fs::write(&a, lower).unwrap();
4251 std::fs::write(&b, upper).unwrap();
4252 Config::load_layers(&[a, b])
4253 }
4254
4255 #[test]
4256 fn graph_implementers_higher_layer_wins_across_spellings() {
4257 let c = layered("[graph]\ncandidates = 2\n", "[graph]\nimplementers = 5\n").unwrap();
4258 assert_eq!(c.graph.implementers, 5);
4259 let c = layered("[graph]\nimplementers = 2\n", "[graph]\ncandidates = 5\n").unwrap();
4260 assert_eq!(c.graph.implementers, 5);
4261 let c = layered("[graph]\ncandidates = 2\n", "[graph]\njudges = 3\n").unwrap();
4262 assert_eq!(c.graph.implementers, 2);
4263 }
4264
4265 #[test]
4266 fn graph_implementers_both_keys_in_one_layer_is_refused() {
4267 let err = layered("", "[graph]\ncandidates = 2\nimplementers = 3\n")
4268 .unwrap_err()
4269 .to_string();
4270 assert!(
4271 err.contains("candidates") && err.contains("implementers"),
4272 "{err}"
4273 );
4274 assert!(err.contains("b.toml"), "{err}");
4275 }
4276
4277 #[test]
4278 fn a_toml_layer_written_before_these_fields_existed_still_parses() {
4279 let g: Graph =
4283 toml::from_str("candidates = 1\nreviewers = 3\nreview_rounds = 6\nmax_parallel = 4\n")
4284 .expect("an old-shaped [graph] table must still parse");
4285 assert_eq!(g.verify_timeout(), Graph::default().timeout_review);
4286 assert!(
4287 !g.e2e_every_round,
4288 "off by default, same as before this field existed"
4289 );
4290 }
4291
4292 #[test]
4293 fn empty_roles_rotate_judges_off_their_own_candidate() {
4294 let cfg = Config {
4297 agents: vec![spec("a"), spec("b"), spec("c")],
4298 graph: Graph {
4299 implementers: 3,
4300 ..Graph::default()
4301 },
4302 ..Config::default()
4303 };
4304 let roles = cfg.resolve_roles().unwrap();
4305 let impls: Vec<&str> = roles.implementers.iter().map(|a| a.id.as_str()).collect();
4306 let judges: Vec<&str> = roles.judges.iter().map(|a| a.id.as_str()).collect();
4307 assert_eq!(impls, ["a", "b", "c"]);
4308 assert_eq!(judges, ["b", "c", "a"]);
4309 for (i, j) in judges.iter().enumerate() {
4310 assert_ne!(*j, impls[i], "judge {i} must not sit on its own candidate");
4311 }
4312 }
4313
4314 #[test]
4315 fn single_agent_roster_fills_every_seat() {
4316 let cfg = Config {
4317 agents: vec![spec("solo")],
4318 graph: Graph {
4319 implementers: 3,
4320 ..Graph::default()
4321 },
4322 ..Config::default()
4323 };
4324 let roles = cfg.resolve_roles().unwrap();
4325 assert_eq!(roles.implementers.len(), 3);
4326 assert!(roles.judges.iter().all(|a| a.id == "solo"));
4327 }
4328
4329 #[test]
4330 fn implementer_roster_is_the_whole_agent_list_untruncated_when_unset() {
4331 let cfg = Config {
4336 agents: vec![spec("a"), spec("b"), spec("c")],
4337 graph: Graph {
4338 implementers: 1,
4339 ..Graph::default()
4340 },
4341 ..Config::default()
4342 };
4343 let roles = cfg.resolve_roles().unwrap();
4344 assert_eq!(roles.implementers.len(), 1);
4345 let roster: Vec<&str> = roles
4346 .implementer_roster
4347 .iter()
4348 .map(|a| a.id.as_str())
4349 .collect();
4350 assert_eq!(roster, ["a", "b", "c"]);
4351 }
4352
4353 #[test]
4354 fn implementer_roster_follows_explicit_ids_in_the_order_named() {
4355 let cfg = Config {
4356 agents: vec![spec("a"), spec("b"), spec("c")],
4357 roles: Roles {
4358 implementers: vec!["c".to_owned(), "a".to_owned()],
4359 ..Roles::default()
4360 },
4361 graph: Graph {
4362 implementers: 1,
4363 ..Graph::default()
4364 },
4365 ..Config::default()
4366 };
4367 let roles = cfg.resolve_roles().unwrap();
4368 assert_eq!(roles.implementers.len(), 1);
4370 assert_eq!(roles.implementers[0].id, "c");
4371 let roster: Vec<&str> = roles
4372 .implementer_roster
4373 .iter()
4374 .map(|a| a.id.as_str())
4375 .collect();
4376 assert_eq!(roster, ["c", "a"]);
4377 }
4378
4379 #[test]
4380 fn explicit_roles_win() {
4381 let cfg = Config {
4382 agents: vec![spec("a"), spec("b")],
4383 roles: Roles {
4384 implementers: vec!["b".to_owned()],
4385 judges: vec!["a".to_owned()],
4386 reviewers: Vec::new(),
4387 fixer: Some("a".into()),
4388 ..Roles::default()
4389 },
4390 ..Config::default()
4391 };
4392 let roles = cfg.resolve_roles().unwrap();
4393 assert!(roles.implementers.iter().all(|a| a.id == "b"));
4394 assert!(roles.judges.iter().all(|a| a.id == "a"));
4395 let fixer = roles.fixer.unwrap();
4396 assert_eq!(fixer.len(), 1);
4397 assert_eq!(fixer[0].id, "a");
4398 assert_eq!(roles.conductor.id, "a");
4399 }
4400
4401 #[test]
4402 fn fixer_takes_a_string_or_an_ordered_chain() {
4403 let one: Roles = toml::from_str("fixer = \"a\"").unwrap();
4404 assert_eq!(one.fixer.as_ref().unwrap().ids(), ["a"]);
4405 let chain: Roles = toml::from_str("fixer = [\"b\", \"a\"]").unwrap();
4406 assert_eq!(chain.fixer.as_ref().unwrap().ids(), ["b", "a"]);
4407
4408 let resolve = |fixer: Option<AgentChoice>| {
4409 Config {
4410 agents: vec![spec("a"), spec("b"), spec("c")],
4411 roles: Roles {
4412 fixer,
4413 ..Roles::default()
4414 },
4415 ..Config::default()
4416 }
4417 .resolve_roles()
4418 };
4419 let ids = |r: &ResolvedRoles| -> Vec<String> {
4420 r.fixer
4421 .as_ref()
4422 .unwrap()
4423 .iter()
4424 .map(|s| s.id.clone())
4425 .collect()
4426 };
4427 assert_eq!(ids(&resolve(Some("c".into())).unwrap()), ["c"]);
4429 assert!(resolve(None).unwrap().fixer.is_none());
4430 let chain = AgentChoice::Chain(vec!["b".into(), "zzz".into(), "a".into(), "b".into()]);
4432 assert_eq!(ids(&resolve(Some(chain)).unwrap()), ["b", "a"]);
4433 let err = resolve(Some(AgentChoice::Chain(vec!["zzz".into()]))).unwrap_err();
4435 assert!(format!("{err:#}").contains("fixer"), "{err:#}");
4436 }
4437
4438 #[test]
4439 fn unknown_agent_id_is_an_error() {
4440 let cfg = Config {
4441 agents: vec![spec("a")],
4442 roles: Roles {
4443 judges: vec!["nope".to_owned()],
4444 ..Roles::default()
4445 },
4446 ..Config::default()
4447 };
4448 assert!(cfg.resolve_roles().is_err());
4449 }
4450
4451 #[test]
4452 fn conductor_role_is_resolved_validated_and_has_a_fallback() {
4453 let mut cfg = Config {
4454 agents: vec![spec("a"), spec("b")],
4455 ..Config::default()
4456 };
4457 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "a");
4458
4459 cfg.roles.conductor = Some("b".into());
4460 assert_eq!(cfg.resolve_roles().unwrap().conductor.id, "b");
4461
4462 cfg.roles.conductor = Some("missing".into());
4463 assert!(cfg.resolve_roles().is_err());
4464 }
4465
4466 #[test]
4467 fn a_standalone_role_takes_a_string_or_an_array_and_round_trips() {
4468 let one: Roles = toml::from_str("synthesizer = \"opus\"").unwrap();
4469 assert_eq!(one.synthesizer, Some(AgentChoice::One("opus".to_owned())));
4470 assert_eq!(primary(one.synthesizer.as_ref()), Some("opus"));
4471
4472 let chain: Roles = toml::from_str("chatter = [\"opus\", \"codex\"]").unwrap();
4473 assert_eq!(chain.chatter.as_ref().unwrap().ids(), ["opus", "codex"]);
4474 assert_eq!(primary(chain.chatter.as_ref()), Some("opus"));
4475
4476 for roles in [one, chain] {
4477 let text = toml::to_string(&roles).unwrap();
4478 let back: Roles = toml::from_str(&text).unwrap();
4479 assert_eq!(back.synthesizer, roles.synthesizer);
4480 assert_eq!(back.chatter, roles.chatter);
4481 }
4482 let text = toml::to_string(&Roles {
4483 conductor: Some("x".into()),
4484 ..Roles::default()
4485 })
4486 .unwrap();
4487 assert!(
4488 text.contains("conductor = \"x\""),
4489 "string stays a string: {text}"
4490 );
4491 assert!(toml::from_str::<Roles>("synthesizer = 3").is_err());
4492 }
4493
4494 #[test]
4495 fn dupes_judge_role_accepts_strings_and_chains_and_round_trips() {
4496 for (text, ids) in [
4497 (r#"dupes_judge = "dedicated""#, vec!["dedicated"]),
4498 (
4499 r#"dupes_judge = ["first", "second"]"#,
4500 vec!["first", "second"],
4501 ),
4502 ("dupes_judge = []", vec![]),
4503 ] {
4504 let roles: Roles = toml::from_str(text).unwrap();
4505 assert_eq!(roles.dupes_judge.as_ref().unwrap().ids(), ids);
4506 let serialized = toml::to_string(&roles).unwrap();
4507 let back: Roles = toml::from_str(&serialized).unwrap();
4508 assert_eq!(back.dupes_judge, roles.dupes_judge);
4509 assert!(serialized.contains(text));
4510 }
4511 assert!(toml::from_str::<Roles>("dupes_judge = 3").is_err());
4512 assert!(Roles::default().dupes_judge.is_none());
4513 assert!(Config::starter_toml().contains("# dupes_judge ="));
4514
4515 let mut cfg = Config {
4517 agents: vec![spec("a")],
4518 ..Config::default()
4519 };
4520 cfg.roles.dupes_judge = Some("missing".into());
4521 assert!(cfg.resolve_roles().is_ok());
4522 }
4523
4524 #[test]
4525 fn an_empty_choice_counts_as_unset() {
4526 assert!(AgentChoice::Chain(Vec::new()).ids().is_empty());
4527 assert!(AgentChoice::One(" ".to_owned()).ids().is_empty());
4528 assert_eq!(primary(Some(&AgentChoice::Chain(vec![]))), None);
4529 }
4530
4531 #[test]
4532 fn synthesizer_role_is_a_lazy_lookup_with_the_same_fallback_as_chatter() {
4533 let mut cfg = Config {
4539 agents: vec![spec("a"), spec("b")],
4540 ..Config::default()
4541 };
4542 let want = primary(cfg.roles.synthesizer.as_ref());
4543 assert_eq!(
4544 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
4545 .unwrap()
4546 .id,
4547 "a",
4548 "unset falls back to agent::pick's own default order"
4549 );
4550
4551 cfg.roles.synthesizer = Some("b".into());
4552 let want = primary(cfg.roles.synthesizer.as_ref());
4553 assert_eq!(
4554 crate::agent::pick(&cfg.agents, want, &crate::agent::installed)
4555 .unwrap()
4556 .id,
4557 "b",
4558 "the named agent wins over the default order"
4559 );
4560 }
4561
4562 #[test]
4563 fn empty_roster_is_an_error() {
4564 assert!(Config::default().resolve_roles().is_err());
4565 }
4566
4567 #[test]
4568 fn advise_defaults_to_on_with_three_proposals() {
4569 let g = Graph::default();
4570 assert!(g.advise);
4571 assert!(g.graft_runner_up, "graft is on by default");
4572 assert_eq!(g.advisors, 3);
4573 }
4574
4575 #[test]
4576 fn unset_advisors_falls_back_to_the_judge_roster() {
4577 let cfg = Config {
4578 agents: vec![spec("a"), spec("b")],
4579 roles: Roles {
4580 judges: vec!["b".to_owned()],
4581 ..Roles::default()
4582 },
4583 graph: Graph {
4584 advisors: 2,
4585 ..Graph::default()
4586 },
4587 ..Config::default()
4588 };
4589 let advisors = cfg.advisors().expect("advisors resolve");
4590 assert_eq!(advisors.len(), 2);
4591 assert!(
4592 advisors.iter().all(|a| a.id == "b"),
4593 "an unset [roles] advisors must fall back to [roles] judges: {advisors:?}"
4594 );
4595 }
4596
4597 #[test]
4598 fn an_explicit_advisor_roster_wins_over_the_judge_fallback() {
4599 let cfg = Config {
4600 agents: vec![spec("a"), spec("b")],
4601 roles: Roles {
4602 judges: vec!["b".to_owned()],
4603 advisors: vec!["a".to_owned()],
4604 ..Roles::default()
4605 },
4606 graph: Graph {
4607 advisors: 2,
4608 ..Graph::default()
4609 },
4610 ..Config::default()
4611 };
4612 let advisors = cfg.advisors().expect("advisors resolve");
4613 assert!(advisors.iter().all(|a| a.id == "a"));
4614 }
4615
4616 #[test]
4622 fn an_unconfigured_advisor_and_judge_roster_resolve_to_the_same_agents() {
4623 let cfg = Config {
4624 agents: vec![spec("a"), spec("b"), spec("c")],
4625 graph: Graph {
4626 advisors: 3,
4627 judges: 3,
4628 ..Graph::default()
4629 },
4630 ..Config::default()
4631 };
4632 let advisors = cfg.advisors().expect("advisors resolve");
4633 let judges = cfg.resolve_roles().expect("roles resolve").judges;
4634 let advisor_ids: Vec<&str> = advisors.iter().map(|a| a.id.as_str()).collect();
4635 let judge_ids: Vec<&str> = judges.iter().map(|a| a.id.as_str()).collect();
4636 assert_eq!(
4637 advisor_ids, judge_ids,
4638 "an unconfigured advisor roster must be the same seats an unconfigured judge panel gets"
4639 );
4640 }
4641
4642 #[test]
4643 fn an_unresolvable_advisor_seat_is_an_error_naming_the_id() {
4644 let cfg = Config {
4645 agents: vec![spec("a")],
4646 roles: Roles {
4647 advisors: vec!["nope".to_owned()],
4648 ..Roles::default()
4649 },
4650 graph: Graph {
4651 advisors: 1,
4652 ..Graph::default()
4653 },
4654 ..Config::default()
4655 };
4656 let err = cfg.advisors().expect_err("`nope` is not in the roster");
4657 assert!(format!("{err:#}").contains("nope"));
4658 }
4659
4660 #[test]
4661 fn repos_default_to_no_roots_and_a_day_of_trust() {
4662 assert_eq!(Config::default().repos.roots, Vec::<PathBuf>::new());
4663 assert_eq!(Config::default().repos.scan_ttl, 86_400);
4664 assert_eq!(Config::default().repos.fetch_interval, 600);
4665 assert!(!Config::default().repos.auto_clone);
4666 assert!(Config::default().repos.clone_command.is_none());
4667 }
4668
4669 #[test]
4670 fn a_config_file_with_no_repos_table_still_loads() {
4671 let dir = tempfile::tempdir().unwrap();
4672 let path = dir.path().join("magi.toml");
4673 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
4674 let cfg = Config::load(&path).expect("must load without [repos]");
4675 assert_eq!(cfg.repos.roots, Vec::<PathBuf>::new());
4676 assert_eq!(cfg.repos.scan_ttl, 86_400);
4677 }
4678
4679 #[test]
4694 fn a_test_build_does_not_read_the_operators_machine_config() {
4695 let repo = tempfile::tempdir().unwrap();
4696 std::fs::write(repo.path().join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
4697
4698 let layers = Config::layers(repo.path());
4699 assert_eq!(
4700 layers,
4701 vec![repo.path().join("magi.toml")],
4702 "only the fixture's own file may be a layer"
4703 );
4704 if let Some(real) = dirs::config_dir() {
4705 let machine = real.join("magi").join("config.toml");
4706 assert!(
4707 !layers.contains(&machine),
4708 "the operator's {} must not be a layer in a test build",
4709 machine.display()
4710 );
4711 }
4712 }
4713
4714 #[test]
4715 fn auto_upgrade_config_defaults_and_opt_in() {
4716 let default: Update = toml::from_str("").unwrap();
4717 assert!(!default.auto_restart);
4718 assert_eq!(default.mode, UpdateMode::Notify);
4719 let enabled: Update = toml::from_str("auto_restart = true\ninterval = \"2h\"\n").unwrap();
4720 assert!(enabled.auto_restart);
4721 assert_eq!(enabled.interval.as_deref(), Some("2h"));
4722 assert!(toml::from_str::<Update>("auto_restart = \"yes\"").is_err());
4723 }
4724
4725 #[test]
4726 fn starter_toml_loads_through_teravars() {
4727 let dir = tempfile::tempdir().unwrap();
4728 let path = dir.path().join("magi.toml");
4729 std::fs::write(&path, Config::starter_toml()).unwrap();
4730 let parsed = Config::load(&path).expect("starter config must load");
4731 assert_eq!(parsed.graph.implementers, 3);
4732 assert_eq!(parsed.merge.mode, MergeMode::None);
4733 assert_eq!(parsed.merge.style, MergeStyle::Merge);
4734 assert!(parsed.graph.sessions);
4735 assert!(parsed.graph.github_text_guard);
4736 assert_eq!(parsed.graph.timeout_review, 1200);
4737 assert_eq!(parsed.graph.verify_timeout(), 1200);
4738 assert_eq!(parsed.update.mode, UpdateMode::Notify);
4739 }
4740
4741 #[test]
4742 fn release_defaults_to_actions_and_the_starter_documents_it() {
4743 let dir = tempfile::tempdir().unwrap();
4744 let path = dir.path().join("magi.toml");
4745 std::fs::write(&path, Config::starter_toml()).unwrap();
4746 let r = Config::load(&path).unwrap().release;
4747 assert_eq!(r.mode, ReleaseMode::Actions);
4748 assert!(!r.is_local());
4749 assert!(r.commands.is_empty());
4750 assert_eq!(r.timeout_minutes, 30);
4751 assert!(Config::starter_toml().contains("# mode = \"actions\""));
4752 }
4753
4754 #[test]
4755 fn release_local_parses_and_unknown_keys_are_refused() {
4756 let dir = tempfile::tempdir().unwrap();
4757 let path = dir.path().join("magi.toml");
4758 std::fs::write(
4759 &path,
4760 "[release]\nmode = \"local\"\ncommands = [\"true\", \"echo $MAGI_RELEASE_TAG\"]\ntimeout_minutes = 5\n",
4761 )
4762 .unwrap();
4763 let r = Config::load(&path).unwrap().release;
4764 assert!(r.is_local());
4765 assert_eq!(r.commands.len(), 2);
4766 assert_eq!(r.timeout_minutes, 5);
4767 std::fs::write(&path, "[release]\nmode = \"local\"\nbogus = 1\n").unwrap();
4768 assert!(Config::load(&path).is_err());
4769 std::fs::write(&path, "[release]\nmode = \"gha\"\n").unwrap();
4770 assert!(Config::load(&path).is_err());
4771 }
4772
4773 #[test]
4774 fn pre_gate_defaults_to_empty_and_the_starter_documents_it() {
4775 let dir = tempfile::tempdir().unwrap();
4776 let path = dir.path().join("magi.toml");
4777 std::fs::write(&path, Config::starter_toml()).unwrap();
4778 assert!(Config::load(&path).unwrap().verify.pre_gate.is_empty());
4779 assert!(Config::starter_toml().contains("# pre_gate = []"));
4780 }
4781
4782 #[test]
4783 fn release_version_files_parse_default_empty_and_are_validated() {
4784 let dir = tempfile::tempdir().unwrap();
4785 let path = dir.path().join("magi.toml");
4786 std::fs::write(&path, "").unwrap();
4787 assert!(
4788 Config::load(&path)
4789 .unwrap()
4790 .release
4791 .version_files
4792 .is_empty()
4793 );
4794 std::fs::write(
4795 &path,
4796 "[release]\nversion_files = [\n{ path = \"src-tauri/Cargo.toml\", kind = \"cargo\" },\n{ path = \"package.json\", kind = \"json\" },\n]\n",
4797 )
4798 .unwrap();
4799 let files = Config::load(&path).unwrap().release.version_files;
4800 assert_eq!(files.len(), 2);
4801 assert_eq!(files[1].kind, VersionKind::Json);
4802 for bad in [
4803 "{ path = \"package.json\", kind = \"json\" }",
4804 "{ path = \"../Cargo.toml\", kind = \"cargo\" }",
4805 "{ path = \"Cargo.toml\", kind = \"cargo\", extra = 1 }",
4806 "{ path = \"Cargo.toml\", kind = \"yaml\" }",
4807 ] {
4808 std::fs::write(&path, format!("[release]\nversion_files = [{bad}]\n")).unwrap();
4809 assert!(Config::load(&path).is_err(), "{bad}");
4810 }
4811 assert!(Config::starter_toml().contains("# version_files = ["));
4812 }
4813
4814 #[test]
4815 fn starter_toml_explains_inherited_and_explicit_verify_timeouts() {
4816 let starter = Config::starter_toml();
4817 assert!(starter.contains("When timeout_verify is omitted, E2E and"));
4818 assert!(starter.contains("verification independent if timeout_review changes later"));
4819 assert!(starter.contains("# timeout_verify = 1200"));
4820 }
4821
4822 #[test]
4823 fn starter_toml_documents_chat_personas() {
4824 let starter = Config::starter_toml();
4825 assert!(starter.contains("# [[talk.personas]]"));
4826 assert!(starter.contains("tone only"));
4827 }
4828
4829 #[test]
4830 fn talk_personas_parse_and_are_validated() {
4831 let dir = tempfile::tempdir().unwrap();
4832 let path = dir.path().join("magi.toml");
4833 std::fs::write(
4834 &path,
4835 "[[talk.personas]]\nid = \"rei\"\nname = \"Quiet\"\nprompt = \"Be brief.\"\n\n\
4836 [[talk.personas]]\nid = \"gendo\"\nname = \"Gendo\"\nprompt = \"Be cold.\"\n",
4837 )
4838 .unwrap();
4839 let cfg = Config::load(&path).expect("loads");
4840 assert_eq!(cfg.talk.personas.len(), 2);
4841 let catalog = crate::persona::catalog(&cfg.talk.personas);
4842 let rei = catalog.iter().find(|p| p.id == "rei").unwrap();
4843 assert_eq!(
4844 (rei.name.as_str(), rei.prompt.as_str()),
4845 ("Quiet", "Be brief.")
4846 );
4847 assert_eq!(catalog.last().unwrap().id, "gendo");
4848
4849 for (body, needle) in [
4850 (
4851 "[[talk.personas]]\nid = \"\"\nname = \"n\"\nprompt = \"p\"\n",
4852 "empty `id`",
4853 ),
4854 (
4855 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \" \"\n",
4856 "empty `prompt`",
4857 ),
4858 (
4859 "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n\
4860 [[talk.personas]]\nid = \"a\"\nname = \"m\"\nprompt = \"q\"\n",
4861 "more than once",
4862 ),
4863 (
4864 "[[talk.personas]]\nid = \"default\"\nname = \"n\"\nprompt = \"p\"\n",
4865 "cannot be redefined",
4866 ),
4867 ] {
4868 std::fs::write(&path, body).unwrap();
4869 let err = format!("{:#}", Config::load(&path).unwrap_err());
4870 assert!(err.contains(needle), "{needle}: {err}");
4871 }
4872 }
4873
4874 #[test]
4875 fn talk_operator_name_is_trimmed_and_validated() {
4876 let dir = tempfile::tempdir().unwrap();
4877 let path = dir.path().join("magi.toml");
4878 let load = |body: &str| {
4879 std::fs::write(&path, body).unwrap();
4880 Config::load(&path)
4881 };
4882 let ok = load("[talk]\noperator_name = \" Commander \"\n").expect("ok");
4883 assert_eq!(ok.talk.operator_name(), Some("Commander"));
4884 let blank = load("[talk]\noperator_name = \" \"\n").expect("blank");
4885 assert_eq!(blank.talk.operator_name(), None);
4886 assert!(load("[talk]\noperator_name = \"a\\nb\"\n").is_err());
4887 let long = "x".repeat(65);
4888 assert!(load(&format!("[talk]\noperator_name = \"{long}\"\n")).is_err());
4889 }
4890
4891 #[test]
4892 fn talk_persona_icon_parses_and_a_bad_shape_keeps_config_usable() {
4893 let dir = tempfile::tempdir().unwrap();
4894 let load = |body: &str| {
4895 let path = dir.path().join("c.toml");
4896 std::fs::write(&path, body).unwrap();
4897 Config::load(&path)
4898 };
4899 let ok = load(
4900 "[[talk.personas]]\nid = \"rei\"\nicon = \"~/rei.png\"\n\n\
4901 [[talk.personas]]\nid = \"default\"\nicon = \"data:image/png;base64,AAAA\"\n",
4902 )
4903 .unwrap();
4904 let c = crate::persona::catalog(&ok.talk.personas);
4905 assert_eq!(c[0].icon.as_deref(), Some("data:image/png;base64,AAAA"));
4906 assert_eq!(c[2].icon.as_deref(), Some("~/rei.png"));
4907 assert!(c[2].prompt.contains("Rei"), "built-in voice kept");
4908 let oversized = format!(
4909 "data:image/png;base64,{}",
4910 "A".repeat(crate::persona_icon::ICON_MAX_BYTES)
4911 );
4912 for bad in ["", "rei.png", "/a/b.svg", "/a/../b.png", &oversized] {
4913 for (id, fields) in [
4914 ("rei", ""),
4915 ("default", ""),
4916 ("custom", "name = \"Custom\"\nprompt = \"Keep calm\"\n"),
4917 ] {
4918 let body = format!("[[talk.personas]]\nid = \"{id}\"\nicon = \"{bad}\"\n{fields}");
4919 let cfg = load(&body).expect("bad icon must not invalidate config");
4920 let persona = crate::persona::find(&cfg.talk.personas, id).unwrap();
4921 assert_eq!(persona.id, id);
4922 assert!(crate::persona_icon::load(bad).is_err());
4923 }
4924 }
4925 let doc = Config::starter_toml();
4926 assert!(doc.contains("# icon = "));
4927 }
4928
4929 #[test]
4930 fn talk_personas_in_two_layers_are_refused() {
4931 let dir = tempfile::tempdir().unwrap();
4932 let machine = dir.path().join("machine.toml");
4933 let repo = dir.path().join("repo.toml");
4934 let one = "[[talk.personas]]\nid = \"a\"\nname = \"n\"\nprompt = \"p\"\n";
4935 std::fs::write(&machine, one).unwrap();
4936 std::fs::write(&repo, one.replace("\"a\"", "\"b\"")).unwrap();
4937 let err = format!("{:#}", Config::load_layers(&[machine, repo]).unwrap_err());
4938 assert!(err.contains("talk.personas"), "{err}");
4939 }
4940
4941 #[test]
4942 fn starter_toml_documents_role_lists_as_backup_order() {
4943 let starter = Config::starter_toml();
4944 assert!(starter.contains("also an ordered backup list"));
4945 assert!(starter.contains("codex then sonnet are spares"));
4946 }
4947
4948 #[test]
4952 fn a_repository_can_declare_a_linear_history_merge_style() {
4953 let dir = tempfile::tempdir().unwrap();
4954 let path = dir.path().join("magi.toml");
4955 std::fs::write(&path, "[merge]\nmode = \"none\"\nstyle = \"squash\"\n").unwrap();
4956 let parsed = Config::load(&path).expect("config must load");
4957 assert_eq!(parsed.merge.style, MergeStyle::Squash);
4958 }
4959
4960 #[test]
4961 fn later_layers_win_and_vars_render() {
4962 let dir = tempfile::tempdir().unwrap();
4963 let machine = dir.path().join("machine.toml");
4964 let project = dir.path().join("magi.toml");
4965 std::fs::write(
4967 &machine,
4968 "[[agents]]\nid = \"opus\"\nkind = \"claude\"\nmodel = \"opus\"\n\n\
4969 [graph]\ncandidates = 3\nmax_parallel = 8\n[verify]\nbuild_cache = \"shared\"\n",
4970 )
4971 .unwrap();
4972 std::fs::write(
4975 &project,
4976 "[vars]\ncache = \"/shared\"\n\n\
4977 [graph]\ncandidates = 2\n\n\
4978 [verify]\nbuild_cache = \"isolated\"\n\
4979 gate = [\"CARGO_TARGET_DIR={{ vars.cache }}/t cargo test\"]\n",
4980 )
4981 .unwrap();
4982
4983 let cfg = Config::load_layers(&[machine, project]).expect("layered load");
4984 assert_eq!(cfg.agents.len(), 1, "roster comes from the machine layer");
4985 assert_eq!(cfg.graph.implementers, 2, "project layer wins");
4986 assert_eq!(cfg.graph.max_parallel, 8, "machine layer survives");
4987 assert_eq!(cfg.verify.build_cache, BuildCache::Isolated);
4988 assert_eq!(
4989 cfg.verify.gate,
4990 ["CARGO_TARGET_DIR=/shared/t cargo test".to_owned()]
4991 );
4992 assert_eq!(cfg.cache_dir(), Some(PathBuf::from("/shared/t")));
4994 }
4995
4996 #[test]
4997 fn saved_config_without_a_build_cache_policy_remains_shared() {
4998 let saved: Config = serde_json::from_str(r#"{"verify":{"gate":["cargo test"]}}"#).unwrap();
4999 assert_eq!(saved.verify.build_cache, BuildCache::Shared);
5000 }
5001
5002 #[test]
5003 fn talk_defaults_to_an_hour_and_an_unwritten_config_still_gets_it() {
5004 let g = Graph::default();
5008 assert_eq!(g.timeout_talk, 3600);
5009
5010 let dir = tempfile::tempdir().unwrap();
5011 let path = dir.path().join("magi.toml");
5012 std::fs::write(&path, "[graph]\ncandidates = 2\n").unwrap();
5013 let cfg = Config::load(&path).expect("must load without timeout_talk set");
5014 assert_eq!(cfg.graph.timeout_talk, 3600);
5015 }
5016
5017 #[test]
5018 fn an_overridden_talk_timeout_reaches_the_loaded_config() {
5019 let dir = tempfile::tempdir().unwrap();
5020 let path = dir.path().join("magi.toml");
5021 std::fs::write(&path, "[graph]\ntimeout_talk = 120\n").unwrap();
5022 let cfg = Config::load(&path).expect("must load");
5023 assert_eq!(cfg.graph.timeout_talk, 120);
5024 }
5025
5026 #[test]
5027 fn the_disk_defaults_are_the_measurements_made_up_front() {
5028 let cfg = Config::default();
5029 assert_eq!(cfg.disk.min_free_bytes, 8 * 1024 * 1024 * 1024);
5030 assert!(cfg.disk.auto_fold);
5031 assert_eq!(cfg.disk.fold_grace_secs, 6 * 60 * 60);
5032 assert_eq!(cfg.disk.cache_limit_bytes, 10 * 1024 * 1024 * 1024);
5033 }
5034
5035 #[test]
5036 fn an_unset_disk_section_is_the_safe_default() {
5037 let dir = tempfile::tempdir().unwrap();
5038 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
5039 let cfg = Config::load(&dir.path().join("magi.toml")).expect("load");
5040 assert_eq!(cfg.disk, Disk::default());
5041 }
5042
5043 #[test]
5044 fn the_reclaim_threshold_defaults_to_twice_the_floor_and_never_undercuts_it() {
5045 let disk = |min: u64, own: Option<u64>| Disk {
5046 min_free_bytes: min,
5047 reclaim_free_bytes: own,
5048 ..Disk::default()
5049 };
5050 assert_eq!(disk(8, None).reclaim_threshold(), 16);
5051 assert_eq!(Disk::default().reclaim_threshold(), 16 * 1024 * 1024 * 1024);
5052 assert_eq!(disk(8, Some(30)).reclaim_threshold(), 30);
5053 assert_eq!(
5054 disk(8, Some(3)).reclaim_threshold(),
5055 8,
5056 "never below the floor"
5057 );
5058 assert_eq!(disk(8, Some(0)).reclaim_threshold(), 8);
5059 assert_eq!(disk(8, Some(8)).reclaim_threshold(), 8);
5060 assert_eq!(
5061 disk(0, None).reclaim_threshold(),
5062 0,
5063 "gate off: no collection"
5064 );
5065 assert_eq!(
5066 disk(0, Some(0)).reclaim_threshold(),
5067 0,
5068 "explicit 0 resolves like unset: the resolved value decides"
5069 );
5070 assert_eq!(
5071 disk(0, Some(5)).reclaim_threshold(),
5072 5,
5073 "explicit still collects"
5074 );
5075 assert_eq!(disk(u64::MAX, None).reclaim_threshold(), u64::MAX);
5076 }
5077
5078 #[test]
5079 fn reclaim_free_bytes_loads_from_toml_and_older_configs_get_the_default() {
5080 let dir = tempfile::tempdir().unwrap();
5081 let path = dir.path().join("magi.toml");
5082 std::fs::write(&path, "[disk]\nmin_free_bytes = 100\n").unwrap();
5083 let cfg = Config::load(&path).expect("older config loads");
5084 assert_eq!(cfg.disk.reclaim_free_bytes, None);
5085 assert_eq!(cfg.disk.reclaim_threshold(), 200);
5086
5087 std::fs::write(
5088 &path,
5089 "[disk]\nmin_free_bytes = 100\nreclaim_free_bytes = 450\n",
5090 )
5091 .unwrap();
5092 let cfg = Config::load(&path).expect("explicit value loads");
5093 assert_eq!(cfg.disk.reclaim_threshold(), 450);
5094 }
5095
5096 #[test]
5097 fn a_saved_run_config_without_the_field_deserializes_to_the_default() {
5098 let disk = serde_json::to_value(Disk::default()).unwrap();
5101 assert!(disk.get("reclaim_free_bytes").is_none());
5102 let older: Disk = serde_json::from_value(disk).unwrap();
5103 assert_eq!(older, Disk::default());
5104 assert_eq!(older.reclaim_threshold(), 2 * older.min_free_bytes);
5105
5106 let own = Disk {
5107 reclaim_free_bytes: Some(7),
5108 ..Disk::default()
5109 };
5110 let back: Disk = serde_json::from_value(serde_json::to_value(&own).unwrap()).unwrap();
5111 assert_eq!(back.reclaim_free_bytes, Some(7));
5112 }
5113
5114 #[test]
5115 fn env_is_available_to_templates_with_a_default() {
5116 let dir = tempfile::tempdir().unwrap();
5117 let path = dir.path().join("magi.toml");
5118 std::fs::write(
5126 &path,
5127 "[verify]\n\
5128 gate = [\"cache={{ env.MAGI_TEST_UNSET_XYZ | default(value='fallback') }}\", \
5129 \"populated={{ env | length > 0 }}\"]\n",
5130 )
5131 .unwrap();
5132 let cfg = Config::load(&path).expect("env lookup must render");
5133 assert_eq!(cfg.verify.gate[0], "cache=fallback");
5134 assert_eq!(cfg.verify.gate[1], "populated=true");
5135 }
5136
5137 #[test]
5138 fn a_broken_template_names_the_file() {
5139 let dir = tempfile::tempdir().unwrap();
5140 let path = dir.path().join("magi.toml");
5141 std::fs::write(&path, "[graph]\nlanguage = \"{{ nope.\"\n").unwrap();
5142 let err = Config::load(&path).expect_err("must not silently ignore");
5143 assert!(err.to_string().contains("teravars"), "{err}");
5144 }
5145
5146 #[test]
5147 fn tera_syntax_in_comments_is_inert() {
5148 let dir = tempfile::tempdir().unwrap();
5152 let path = dir.path().join("magi.toml");
5153 std::fs::write(
5154 &path,
5155 "# a comment may quote templates: `{{ env.NOPE | default(value='x') }}` and `{% if %}`\n\
5156 [graph]\ncandidates = 2\n",
5157 )
5158 .unwrap();
5159 let cfg = Config::load(&path).expect("comments must be inert, not rendered");
5160 assert_eq!(cfg.graph.implementers, 2);
5161 }
5162
5163 #[test]
5164 fn agent_turn_cap_round_trips_and_never_extends_the_budget() {
5165 use std::time::Duration;
5166
5167 let mut s: AgentSpec =
5168 toml::from_str("id = 'slow'\nkind = 'command'\ncommand = ['true']\n").unwrap();
5169 let budget = Duration::from_millis(1500);
5170 assert_eq!(s.max_turn_secs, None);
5171 assert_eq!(s.turn_timeout(budget), budget);
5172 assert!(!toml::to_string(&s).unwrap().contains("max_turn_secs"));
5173 for (cap, expected) in [
5174 (1, Duration::from_secs(1)),
5175 (2, budget),
5176 (0, Duration::ZERO),
5177 ] {
5178 s.max_turn_secs = Some(cap);
5179 let saved = toml::to_string(&s).unwrap();
5180 let loaded: AgentSpec = toml::from_str(&saved).unwrap();
5181 assert_eq!(loaded.max_turn_secs, Some(cap));
5182 assert_eq!(loaded.turn_timeout(budget), expected);
5183 }
5184 }
5185
5186 #[test]
5187 fn opencode_defaults_to_file_delivery() {
5188 let mut s = spec("oc");
5189 s.kind = AgentKind::Opencode;
5190 assert_eq!(s.delivery(), Delivery::File);
5191 s.prompt_delivery = Some(Delivery::Argv);
5192 assert_eq!(s.delivery(), Delivery::Argv);
5193 }
5194 #[test]
5195 fn the_land_loop_is_on_but_it_cannot_merge_without_being_asked() {
5196 let g = Graph::default();
5201 assert!(
5202 g.land,
5203 "stopping at an open PR left the watching to a human"
5204 );
5205 assert!(
5206 g.land_approval,
5207 "on-by-default land is only defensible while this is also on"
5208 );
5209 assert!(g.land_rounds > 0, "a loop with no budget never terminates");
5210 assert!(
5211 g.hold_contested_merge,
5212 "a contested hand-off must still reach a human when approvals are off"
5213 );
5214 }
5215 #[test]
5216 fn an_array_declared_in_two_layers_is_refused_instead_of_concatenated() {
5217 let dir = tempfile::tempdir().unwrap();
5221 let machine = dir.path().join("machine.toml");
5222 let repo = dir.path().join("magi.toml");
5223 std::fs::write(&machine, "[roles]\nimplementers = [\"a\", \"b\"]\n").unwrap();
5224 std::fs::write(&repo, "[roles]\nimplementers = [\"oc\"]\n").unwrap();
5225
5226 let err = Config::load_layers(&[machine.clone(), repo.clone()])
5227 .expect_err("two layers naming one array must not merge silently");
5228 assert_eq!(
5229 err.downcast_ref::<ConfigFailure>().unwrap().stage,
5230 "config-merge"
5231 );
5232 let err = err.to_string();
5233 assert!(err.contains("roles.implementers"), "{err}");
5234 assert!(err.contains("machine.toml"), "{err}");
5237 assert!(err.contains("magi.toml"), "{err}");
5238 }
5239
5240 #[test]
5241 fn a_scalar_in_one_layer_and_an_array_in_another_still_merges() {
5242 let dir = tempfile::tempdir().unwrap();
5245 let machine = dir.path().join("machine.toml");
5246 let repo = dir.path().join("magi.toml");
5247 std::fs::write(&machine, "[roles]\nchatter = \"opus\"\n").unwrap();
5248 std::fs::write(
5249 &repo,
5250 "[[agents]]\nid = \"oc\"\nkind = \"opencode\"\n\n\
5251 [roles]\nimplementers = [\"oc\"]\n",
5252 )
5253 .unwrap();
5254
5255 let cfg = Config::load_layers(&[machine, repo]).expect("layers merge");
5256 assert_eq!(primary(cfg.roles.chatter.as_ref()), Some("opus"));
5257 assert_eq!(cfg.roles.implementers, ["oc"]);
5258 assert_eq!(cfg.agents.len(), 1, "the roster is not doubled");
5259 }
5260
5261 #[test]
5262 fn two_layers_declaring_verify_gate_run_both_in_priority_order() {
5263 let dir = tempfile::tempdir().unwrap();
5266 let machine = dir.path().join("machine.toml");
5267 let repo = dir.path().join("magi.toml");
5268 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
5269 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
5270
5271 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
5272 assert_eq!(
5273 cfg.verify.gate,
5274 [
5275 "editorconfig-checker".to_owned(),
5276 "cargo make check".to_owned()
5277 ],
5278 "low-priority (machine) command first, high-priority (repo) command after"
5279 );
5280 }
5281
5282 fn load_one(body: &str) -> Result<Config> {
5283 let dir = tempfile::tempdir().unwrap();
5284 let path = dir.path().join("magi.toml");
5285 std::fs::write(&path, body).unwrap();
5286 Config::load_layers(&[path])
5287 }
5288
5289 #[test]
5290 fn pre_clean_config_is_strict_and_single_layer() {
5291 assert!(Config::default().worktree.pre_clean.is_empty());
5292 let good = load_one("[worktree]\npre_clean = [{run = 'cleanup', timeout_secs = 60}]\n");
5293 assert_eq!(good.unwrap().worktree.pre_clean[0].timeout_secs, Some(60));
5294 for bad in [
5295 "{}",
5296 "{run = ''}",
5297 "{run = ' ', timeout_secs = 2}",
5298 "{run = 'x', timeout_secs = 0}",
5299 "{run = 'x', timeout_secs = -1}",
5300 "{copy = 'cache'}",
5301 "{run = 'x', optional = true}",
5302 "'x'",
5303 ] {
5304 assert!(
5305 load_one(&format!("[worktree]\npre_clean = [{bad}]\n")).is_err(),
5306 "{bad}"
5307 );
5308 }
5309 let dir = tempfile::tempdir().unwrap();
5310 let a = dir.path().join("a.toml");
5311 let b = dir.path().join("b.toml");
5312 for path in [&a, &b] {
5313 std::fs::write(path, "[worktree]\npre_clean = [{run = 'cleanup'}]\n").unwrap();
5314 }
5315 assert!(
5316 Config::load_layers(&[a, b])
5317 .unwrap_err()
5318 .to_string()
5319 .contains("worktree.pre_clean")
5320 );
5321 }
5322
5323 #[test]
5324 fn worktree_setup_defaults_to_empty_and_parses_steps() {
5325 assert!(Config::default().worktree.setup.is_empty());
5326 let cfg = load_one(
5327 "[worktree]\nsetup = [\n { copy = \".env.example -> .env\" },\n \
5328 { copy = \"x\", optional = true },\n { run = \"true\", timeout_secs = 5 },\n]\n",
5329 )
5330 .unwrap();
5331 assert_eq!(cfg.worktree.setup.len(), 3);
5332 assert!(cfg.worktree.setup[1].optional);
5333 assert_eq!(cfg.worktree.setup[2].timeout_secs, Some(5));
5334 }
5335
5336 #[test]
5337 fn worktree_setup_rejects_malformed_steps() {
5338 for bad in [
5339 "{ copy = \"a\", run = \"b\" }",
5340 "{ optional = true }",
5341 "{ copy = \"a -> ../b\" }",
5342 "{ copy = \"a -> /abs\" }",
5343 "{ copy = \"a -> .git/config\" }",
5344 "{ run = \"b\", optional = true }",
5345 "{ copy = \"a\", timeout_secs = 3 }",
5346 "{ run = \"b\", bogus = 1 }",
5347 ] {
5348 let body = format!("[worktree]\nsetup = [{bad}]\n");
5349 assert!(load_one(&body).is_err(), "{bad}");
5350 }
5351 }
5352
5353 #[test]
5354 fn worktree_setup_in_two_layers_is_refused() {
5355 let dir = tempfile::tempdir().unwrap();
5356 let machine = dir.path().join("machine.toml");
5357 let repo = dir.path().join("magi.toml");
5358 std::fs::write(&machine, "[worktree]\nsetup = [{ run = \"a\" }]\n").unwrap();
5359 std::fs::write(&repo, "[worktree]\nsetup = [{ run = \"b\" }]\n").unwrap();
5360 assert!(Config::load_layers(&[machine, repo]).is_err());
5361 }
5362
5363 #[test]
5364 fn starter_toml_documents_worktree_setup() {
5365 let starter = Config::starter_toml();
5366 assert!(starter.contains("# [worktree]") && starter.contains("setup = ["));
5367 let body = starter.replace("# [worktree]", "[worktree]");
5369 let mut out = String::new();
5370 let mut live = false;
5371 for line in body.lines() {
5372 if line == "[worktree]" {
5373 live = true;
5374 } else if live && !line.starts_with("# ") {
5375 live = false;
5376 }
5377 out.push_str(&if live {
5378 line.replacen("# ", "", 1)
5379 } else {
5380 line.to_owned()
5381 });
5382 out.push('\n');
5383 }
5384 let cfg = load_one(&out).expect("uncommented example loads");
5385 assert_eq!(cfg.worktree.setup.len(), 3);
5386 }
5387
5388 #[test]
5389 fn two_layers_declaring_verify_e2e_run_both_in_priority_order() {
5390 let dir = tempfile::tempdir().unwrap();
5391 let machine = dir.path().join("machine.toml");
5392 let repo = dir.path().join("magi.toml");
5393 std::fs::write(&machine, "[verify]\ne2e = [\"shared-smoke-test\"]\n").unwrap();
5394 std::fs::write(&repo, "[verify]\ne2e = [\"cargo test\"]\n").unwrap();
5395
5396 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
5397 assert_eq!(
5398 cfg.verify.e2e,
5399 ["shared-smoke-test".to_owned(), "cargo test".to_owned()]
5400 );
5401 }
5402
5403 #[test]
5404 fn two_layers_declaring_repos_roots_are_both_scanned() {
5405 let dir = tempfile::tempdir().unwrap();
5406 let machine = dir.path().join("machine.toml");
5407 let repo = dir.path().join("magi.toml");
5408 std::fs::write(&machine, "[repos]\nroots = [\"/machine/root\"]\n").unwrap();
5409 std::fs::write(&repo, "[repos]\nroots = [\"/repo/root\"]\n").unwrap();
5410
5411 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
5412 assert_eq!(
5413 cfg.repos.roots,
5414 [PathBuf::from("/machine/root"), PathBuf::from("/repo/root")]
5415 );
5416 }
5417
5418 #[test]
5419 fn duplicate_gate_commands_across_layers_both_run() {
5420 let dir = tempfile::tempdir().unwrap();
5423 let machine = dir.path().join("machine.toml");
5424 let repo = dir.path().join("magi.toml");
5425 std::fs::write(&machine, "[verify]\ngate = [\"same-command\"]\n").unwrap();
5426 std::fs::write(&repo, "[verify]\ngate = [\"same-command\"]\n").unwrap();
5427
5428 let cfg = Config::load_layers(&[machine, repo]).expect("appendable arrays must merge");
5429 assert_eq!(
5430 cfg.verify.gate,
5431 ["same-command".to_owned(), "same-command".to_owned()]
5432 );
5433 }
5434
5435 #[test]
5436 fn notify_command_is_still_refused_across_two_layers() {
5437 let dir = tempfile::tempdir().unwrap();
5439 let machine = dir.path().join("machine.toml");
5440 let repo = dir.path().join("magi.toml");
5441 std::fs::write(&machine, "[notify]\ncommand = [\"ntfy\", \"publish\"]\n").unwrap();
5442 std::fs::write(&repo, "[notify]\ncommand = [\"curl\", \"-X\"]\n").unwrap();
5443
5444 let err = Config::load_layers(&[machine.clone(), repo.clone()])
5445 .expect_err("an argv split across layers must not concatenate");
5446 assert_eq!(
5447 err.downcast_ref::<ConfigFailure>().unwrap().stage,
5448 "config-merge"
5449 );
5450 let err = err.to_string();
5451 assert!(err.contains("notify.command"), "{err}");
5452 assert!(err.contains("machine.toml"), "{err}");
5453 assert!(err.contains("magi.toml"), "{err}");
5454 }
5455
5456 #[test]
5457 fn one_layer_declaring_verify_gate_runs_unchanged() {
5458 let dir = tempfile::tempdir().unwrap();
5461 let path = dir.path().join("magi.toml");
5462 std::fs::write(&path, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
5463
5464 let cfg = Config::load(&path).expect("single layer must still load");
5465 assert_eq!(cfg.verify.gate, ["cargo make check".to_owned()]);
5466 }
5467
5468 #[test]
5469 fn layered_parse_failures_name_the_failing_input() {
5470 let dir = tempfile::tempdir().unwrap();
5471 let a = dir.path().join("a.toml");
5472 let b = dir.path().join("b.toml");
5473 std::fs::write(&a, "[graph").unwrap();
5474 std::fs::write(&b, "[verify").unwrap();
5475 let paths = [a.clone(), b.clone()];
5476 let first = Config::load_layers(&paths).unwrap_err();
5477 let first_cause = first.downcast_ref::<ConfigFailure>().unwrap();
5478 assert_eq!(first_cause.stage, "config-parse");
5479 assert_eq!(first_cause.target, serde_json::to_string(&[&a]).unwrap());
5480 std::fs::write(&a, "").unwrap();
5481 let second = Config::load_layers(&paths).unwrap_err();
5482 let second_cause = second.downcast_ref::<ConfigFailure>().unwrap();
5483 assert_eq!(second_cause.stage, "config-parse");
5484 assert_eq!(second_cause.target, serde_json::to_string(&[&b]).unwrap());
5485 assert_ne!(first_cause.target, second_cause.target);
5486 }
5487
5488 #[test]
5489 fn describe_composed_names_the_contributing_layers_only_when_there_are_two() {
5490 let dir = tempfile::tempdir().unwrap();
5491 let machine = dir.path().join("machine.toml");
5492 let repo = dir.path().join("magi.toml");
5493 std::fs::write(&machine, "[verify]\ngate = [\"editorconfig-checker\"]\n").unwrap();
5494 std::fs::write(&repo, "[verify]\ngate = [\"cargo make check\"]\n").unwrap();
5495 let paths = vec![machine.clone(), repo.clone()];
5496
5497 let cfg = Config::load_layers(&paths).expect("appendable arrays must merge");
5498 let described =
5499 Config::describe_composed(&paths, &cfg.verify.gate, "verify.gate", "(none)");
5500 assert!(described.contains("editorconfig-checker && cargo make check"));
5501 assert!(
5502 described.contains(&machine.display().to_string()),
5503 "{described}"
5504 );
5505 assert!(
5506 described.contains(&repo.display().to_string()),
5507 "{described}"
5508 );
5509
5510 let single = vec![repo.clone()];
5512 let solo_cfg = Config::load_layers(&single).expect("single layer loads");
5513 let solo_described =
5514 Config::describe_composed(&single, &solo_cfg.verify.gate, "verify.gate", "(none)");
5515 assert_eq!(solo_described, "cargo make check");
5516 }
5517
5518 mod remote_layers {
5519 use super::*;
5520
5521 fn git(dir: &Path, args: &[&str]) {
5522 use crate::proc::Quiet as _;
5523 let out = std::process::Command::new("git")
5524 .args(args)
5525 .quiet()
5526 .current_dir(dir)
5527 .output()
5528 .unwrap();
5529 assert!(out.status.success(), "git {args:?}: {out:?}");
5530 }
5531
5532 fn fixture(remote: &str, disk: &str) -> (tempfile::TempDir, PathBuf) {
5535 let tmp = tempfile::tempdir().unwrap();
5536 let bare = tmp.path().join("o.git");
5537 git(tmp.path(), &["init", "--bare", "-b", "trunk", "o.git"]);
5538 let repo = tmp.path().join("repo");
5539 std::fs::create_dir_all(&repo).unwrap();
5540 git(&repo, &["init", "-b", "trunk"]);
5541 git(&repo, &["config", "user.name", "t"]);
5542 git(&repo, &["config", "user.email", "t@example.com"]);
5543 std::fs::write(repo.join("magi.toml"), remote).unwrap();
5544 git(&repo, &["add", "-A"]);
5545 git(&repo, &["commit", "-m", "x"]);
5546 git(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
5547 git(&repo, &["push", "origin", "trunk"]);
5548 git(&repo, &["fetch", "origin"]);
5549 git(&repo, &["remote", "set-head", "origin", "trunk"]);
5550 std::fs::write(repo.join("magi.toml"), disk).unwrap();
5551 (tmp, repo)
5552 }
5553
5554 #[tokio::test]
5555 async fn branch_owner_holds_only_add_literal_true_values() {
5556 for (text, expected) in [
5557 ("[graph]\nland_approval = true\n", true),
5558 ("[graph]\nland_approval = false\n", false),
5559 ("[graph]\nland = true\n", false),
5560 ("[graph\n", false),
5561 ("[graph]\nland_approval = \"yes\"\n", false),
5562 ("[graph]\nland_approval = 1\n", false),
5563 ] {
5564 let (_tmp, repo) = fixture(text, "[graph]\nland_approval = false\n");
5565 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
5566 let (holds, _) = branch_owner_holds(&repo, &head).await;
5567 assert_eq!(
5568 holds.contains(&(OwnerHold::LandApproval, "magi.toml".into())),
5569 expected
5570 );
5571 assert!(
5572 !holds
5573 .iter()
5574 .any(|(h, _)| *h == OwnerHold::HoldContestedMerge)
5575 );
5576 for base in [false, true] {
5577 let mut cfg = Config::default();
5578 cfg.graph.land_approval = base;
5579 let mut state = crate::run::RunState::new(
5580 repo.clone(),
5581 "trunk".into(),
5582 head.clone(),
5583 "review".into(),
5584 cfg,
5585 );
5586 state.observe_branch_owner_holds(&head).await;
5587 assert!(
5588 state.branch_owner_holds.is_empty(),
5589 "competition candidates are excluded"
5590 );
5591 state.reviewed_commits = Some(Vec::new());
5592 state.observe_branch_owner_holds(&head).await;
5593 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base || expected);
5594 }
5595 }
5596 }
5597
5598 #[tokio::test]
5599 async fn branch_owner_holds_missing_and_unreadable_preserve_base() {
5600 let (_tmp, repo) = fixture(
5601 "[graph]\nland_approval = true\n",
5602 "[graph]\nland_approval = true\n",
5603 );
5604 git(&repo, &["rm", "magi.toml"]);
5605 std::fs::create_dir(repo.join(".magi")).unwrap();
5606 std::fs::write(
5607 repo.join(".magi/config.toml"),
5608 "[graph]\nhold_contested_merge = true\n",
5609 )
5610 .unwrap();
5611 git(&repo, &["add", "."]);
5612 git(&repo, &["commit", "-m", "nested hold"]);
5613 let head = crate::git::rev_parse(&repo, "HEAD").await.unwrap();
5614 let (holds, _) = branch_owner_holds(&repo, &head).await;
5615 assert_eq!(
5616 holds,
5617 [(OwnerHold::HoldContestedMerge, ".magi/config.toml".into())]
5618 );
5619 let (holds, diagnostics) =
5620 branch_owner_holds(&repo, "0000000000000000000000000000000000000000").await;
5621 assert!(holds.is_empty());
5622 assert!(!diagnostics.is_empty());
5623 let (holds, diagnostics) = branch_owner_holds(&repo, "").await;
5624 assert!(holds.is_empty());
5625 assert!(!diagnostics.is_empty());
5626 for base in [false, true] {
5627 let mut cfg = Config::default();
5628 cfg.graph.land_approval = base;
5629 let mut state = crate::run::RunState::new(
5630 repo.clone(),
5631 "trunk".into(),
5632 head.clone(),
5633 "review".into(),
5634 cfg,
5635 );
5636 state.reviewed_commits = Some(Vec::new());
5637 state.observe_branch_owner_holds(&head).await;
5638 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
5639 state
5640 .observe_branch_owner_holds("0000000000000000000000000000000000000000")
5641 .await;
5642 assert_eq!(state.owner_hold(OwnerHold::LandApproval), base);
5643 }
5644 }
5645
5646 #[test]
5647 fn reads_the_remote_blob_not_the_working_tree() {
5648 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
5649 let (cfg, _) = Config::discover(&repo, None).unwrap();
5650 assert_eq!(cfg.graph.implementers, 2);
5651 }
5652
5653 #[test]
5654 fn detached_head_still_reads_the_remote() {
5655 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
5656 git(&repo, &["checkout", "--detach"]);
5657 let (cfg, _) = Config::discover(&repo, None).unwrap();
5658 assert_eq!(cfg.graph.implementers, 2);
5659 }
5660
5661 #[test]
5662 fn a_missing_ref_is_an_error_not_a_fallback() {
5663 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 5\n");
5664 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
5665 let err = format!("{:#}", Config::discover(&repo, None).unwrap_err());
5666 assert!(err.contains("origin"), "{err}");
5667 }
5668
5669 #[test]
5670 fn merge_base_in_the_checkout_locates_the_ref() {
5671 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
5672 assert!(Config::discover(&repo, None).is_err());
5673 }
5674
5675 #[test]
5676 fn the_magi_dir_layer_is_read_too() {
5677 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
5678 std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
5679 std::fs::create_dir_all(repo.join(".magi")).unwrap();
5680 std::fs::write(repo.join(".magi/config.toml"), "[graph]\njudges = 3\n").unwrap();
5681 git(&repo, &["add", "-A"]);
5682 git(&repo, &["commit", "-m", "y"]);
5683 git(&repo, &["push", "origin", "trunk"]);
5684 git(&repo, &["fetch", "origin"]);
5685 let ((cfg, layers), (_, cold_git)) =
5686 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap());
5687 assert_eq!((cfg.graph.implementers, cfg.graph.judges), (2, 3));
5688 assert_eq!(layers.len(), 2);
5689 assert_eq!(cold_git, 1);
5690 let common_cache = repo
5691 .join(".git")
5692 .canonicalize()
5693 .unwrap()
5694 .join("magi")
5695 .join("config");
5696 assert!(
5697 layers.iter().all(|p| p.starts_with(&common_cache)),
5698 "expected .magi/config.toml and magi.toml to cache under common git dir {}, got {layers:?}",
5699 common_cache.display()
5700 );
5701
5702 let ((cfg_warm, warm_layers), (_, warm_git)) =
5703 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap());
5704 assert_eq!((cfg_warm.graph.implementers, cfg_warm.graph.judges), (2, 3));
5705 assert_eq!(warm_layers, layers);
5706 assert_eq!(warm_git, 1);
5707 }
5708
5709 #[test]
5710 fn an_include_in_a_repository_layer_resolves_against_the_same_commit() {
5711 let (_t, repo) = fixture("include = [\"gate.toml\"]\n", "");
5712 std::fs::write(repo.join("magi.toml"), "include = [\"gate.toml\"]\n").unwrap();
5713 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 2\n").unwrap();
5714 git(&repo, &["add", "-A"]);
5715 git(&repo, &["commit", "-m", "inc"]);
5716 git(&repo, &["push", "origin", "trunk"]);
5717 git(&repo, &["fetch", "origin"]);
5718 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 9\n").unwrap();
5720 let (cfg, _) = Config::discover(&repo, None).unwrap();
5721 assert_eq!(cfg.graph.implementers, 2);
5722 }
5723
5724 #[test]
5725 fn a_machine_layer_base_is_rendered_before_locating_the_ref() {
5726 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[merge]\nbase = \"nope\"\n");
5727 let m = t.path().join("machine.toml");
5728 std::fs::write(
5729 &m,
5730 "[merge]\nbase = \"{{ env.MAGI_TEST_NO_SUCH | default(value='trunk') }}\"\n",
5731 )
5732 .unwrap();
5733 let (remote, base) = {
5734 let probe = probe_merge(&m, &repo).unwrap();
5735 (probe.remote, probe.base)
5736 };
5737 assert_eq!((remote, base), (None, Some("trunk".to_owned())));
5738 }
5739
5740 #[test]
5741 fn a_machine_layer_base_sees_the_checkouts_repo_name() {
5742 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
5743 let m = t.path().join("machine.toml");
5744 std::fs::write(&m, "[merge]\nbase = \"{{ repo_name }}\"\n").unwrap();
5745 let probe = probe_merge(&m, &repo).unwrap();
5746 assert_eq!(probe.base.as_deref(), Some("repo"));
5747 }
5748
5749 #[test]
5750 fn every_include_form_is_recognised() {
5751 assert!(declares_include("include = [\"a.toml\"]\n"));
5752 assert!(declares_include("\"include\" = [\"a.toml\"]\n"));
5753 assert!(declares_include("teravars = { include = [\"a.toml\"] }\n"));
5754 assert!(declares_include("[teravars]\ninclude = [\"a.toml\"]\n"));
5755 assert!(!declares_include("[graph]\ncandidates = 2\n"));
5756 }
5757
5758 #[test]
5759 fn an_explicit_config_is_read_as_named() {
5760 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
5761 let own = t.path().join("own.toml");
5762 std::fs::write(&own, "[graph]\ncandidates = 4\n").unwrap();
5763 let (cfg, _) = Config::discover(&repo, Some(&own)).unwrap();
5764 assert_eq!(cfg.graph.implementers, 4);
5765 }
5766
5767 #[test]
5768 fn discover_fetched_fails_when_the_fetch_does() {
5769 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "");
5770 std::fs::remove_dir_all(t.path().join("o.git")).unwrap();
5771 let rt = tokio::runtime::Builder::new_current_thread()
5772 .enable_all()
5773 .build()
5774 .unwrap();
5775 let err = rt
5776 .block_on(Config::discover_fetched(&repo, None))
5777 .unwrap_err();
5778 assert!(format!("{err:#}").contains("fetch"), "{err:#}");
5779 }
5780
5781 #[test]
5782 fn fetch_and_remote_parse_failures_have_distinct_verified_causes() {
5783 let (tmp, repo) = fixture("[graph\ncandidates = 2\n", "");
5784 let remote = tmp.path().join("o.git");
5785 let offline = tmp.path().join("offline.git");
5786 std::fs::rename(&remote, &offline).unwrap();
5787 let rt = tokio::runtime::Builder::new_current_thread()
5788 .enable_all()
5789 .build()
5790 .unwrap();
5791 let fetch = rt
5792 .block_on(Config::discover_fetched(&repo, None))
5793 .unwrap_err();
5794 let fetch_cause = fetch.downcast_ref::<ConfigFailure>().unwrap();
5795 assert_eq!(fetch_cause.stage, "config-fetch");
5796 assert_eq!(fetch_cause.target, "origin/trunk");
5797
5798 std::fs::rename(&offline, &remote).unwrap();
5799 let parse = rt
5800 .block_on(Config::discover_fetched(&repo, None))
5801 .unwrap_err();
5802 let parse_cause = parse.downcast_ref::<ConfigFailure>().unwrap();
5803 assert_eq!(parse_cause.stage, "config-parse");
5804 assert!(parse_cause.target.contains("magi.toml"));
5805 assert!(
5806 !parse_cause.target.contains("/magi/config/"),
5807 "cache commit paths are incidental"
5808 );
5809 assert_ne!(fetch_cause.stage, parse_cause.stage);
5810 }
5811
5812 #[test]
5813 fn discover_fetched_survives_a_fetch_that_leaves_no_origin_head() {
5814 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "");
5817 git(&repo, &["remote", "set-head", "origin", "-d"]);
5818 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
5819 git(
5820 &repo,
5821 &["config", "remote.origin.followRemoteHEAD", "never"],
5822 );
5823 let rt = tokio::runtime::Builder::new_current_thread()
5824 .enable_all()
5825 .build()
5826 .unwrap();
5827 let (cfg, _) = rt.block_on(Config::discover_fetched(&repo, None)).unwrap();
5828 assert_eq!(cfg.graph.implementers, 2);
5829 }
5830
5831 #[test]
5832 fn a_non_git_directory_reads_its_files() {
5833 let dir = tempfile::tempdir().unwrap();
5834 std::fs::write(dir.path().join("magi.toml"), "[graph]\ncandidates = 4\n").unwrap();
5835 let (cfg, (discoveries, git_calls)) =
5836 crate::web::request_cost::measure_sync(|| Config::discover(dir.path(), None));
5837 assert_eq!(cfg.unwrap().0.graph.implementers, 4);
5838 assert_eq!((discoveries, git_calls), (1, 0));
5839 }
5840
5841 fn push_remote_config(bare: &Path, branch: &str, magi_toml: &str) {
5842 let tmp = tempfile::tempdir().unwrap();
5843 let clone = tmp.path().join("push");
5844 git(
5845 tmp.path(),
5846 &["clone", "-b", branch, &bare.to_string_lossy(), "push"],
5847 );
5848 git(&clone, &["config", "user.name", "t"]);
5849 git(&clone, &["config", "user.email", "t@example.com"]);
5850 std::fs::write(clone.join("magi.toml"), magi_toml).unwrap();
5851 git(&clone, &["add", "magi.toml"]);
5852 git(&clone, &["commit", "-m", "update config"]);
5853 git(&clone, &["push", "origin", branch]);
5854 }
5855
5856 #[test]
5857 fn repeated_discovers_stay_within_bounded_git_spawns() {
5858 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
5859
5860 let (values, (discoveries, cold_git)) = crate::web::request_cost::measure_sync(|| {
5863 (0..20)
5864 .map(|_| Config::discover(&repo, None).unwrap().0.graph.implementers)
5865 .collect::<Vec<_>>()
5866 });
5867 assert!(values.iter().all(|&n| n == 2));
5868 assert_eq!(discoveries, 20);
5869 assert_eq!(cold_git, 21);
5870
5871 let (values, (discoveries, warm_git)) = crate::web::request_cost::measure_sync(|| {
5873 (0..20)
5874 .map(|_| Config::discover(&repo, None).unwrap().0.graph.implementers)
5875 .collect::<Vec<_>>()
5876 });
5877 assert!(values.iter().all(|&n| n == 2));
5878 assert_eq!(discoveries, 20);
5879 assert_eq!(warm_git, 20);
5880 }
5881
5882 #[test]
5883 fn reftable_warm_discover_uses_one_git_process() {
5884 let tmp = tempfile::tempdir().unwrap();
5885 let repo = tmp.path();
5886 git(repo, &["init", "--ref-format=reftable", "-b", "trunk"]);
5887 git(repo, &["config", "user.name", "t"]);
5888 git(repo, &["config", "user.email", "t@example.com"]);
5889 std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 2\n").unwrap();
5890 git(repo, &["add", "magi.toml"]);
5891 git(repo, &["commit", "-m", "config"]);
5892 git(repo, &["update-ref", "refs/remotes/origin/trunk", "HEAD"]);
5893 git(
5894 repo,
5895 &[
5896 "symbolic-ref",
5897 "refs/remotes/origin/HEAD",
5898 "refs/remotes/origin/trunk",
5899 ],
5900 );
5901 assert_eq!(
5902 Config::discover(repo, None).unwrap().0.graph.implementers,
5903 2
5904 );
5905 let (values, (_, count)) = crate::web::request_cost::measure_sync(|| {
5906 (0..10)
5907 .map(|_| Config::discover(repo, None).unwrap().0.graph.implementers)
5908 .collect::<Vec<_>>()
5909 });
5910 assert_eq!(values, vec![2; 10]);
5911 assert_eq!(count, 10);
5912 }
5913
5914 #[test]
5915 fn zero_layer_repository_caches_empty_manifest() {
5916 let tmp = tempfile::tempdir().unwrap();
5917 let bare = tmp.path().join("o.git");
5918 git(tmp.path(), &["init", "--bare", "-b", "trunk", "o.git"]);
5919 let repo = tmp.path().join("repo");
5920 std::fs::create_dir_all(&repo).unwrap();
5921 git(&repo, &["init", "-b", "trunk"]);
5922 git(&repo, &["config", "user.name", "t"]);
5923 git(&repo, &["config", "user.email", "t@example.com"]);
5924 std::fs::write(repo.join("README.md"), "hello\n").unwrap();
5925 git(&repo, &["add", "-A"]);
5926 git(&repo, &["commit", "-m", "no config"]);
5927 git(&repo, &["remote", "add", "origin", &bare.to_string_lossy()]);
5928 git(&repo, &["push", "origin", "trunk"]);
5929 git(&repo, &["fetch", "origin"]);
5930 git(&repo, &["remote", "set-head", "origin", "trunk"]);
5931
5932 let (layers, (_, cold_git)) = crate::web::request_cost::measure_sync(|| {
5933 let mut last = Vec::new();
5934 for _ in 0..20 {
5935 last = Config::discover(&repo, None).unwrap().1;
5936 }
5937 last
5938 });
5939 assert!(layers.is_empty());
5940 assert_eq!(cold_git, 21);
5941
5942 let (layers, (_, warm_git)) = crate::web::request_cost::measure_sync(|| {
5943 let mut last = Vec::new();
5944 for _ in 0..20 {
5945 last = Config::discover(&repo, None).unwrap().1;
5946 }
5947 last
5948 });
5949 assert!(layers.is_empty());
5950 assert_eq!(warm_git, 20);
5951 }
5952
5953 #[test]
5954 fn moved_loose_and_packed_refs_are_observed_immediately() {
5955 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
5956 let bare = t.path().join("o.git");
5957
5958 assert_eq!(
5960 Config::discover(&repo, None).unwrap().0.graph.implementers,
5961 2
5962 );
5963 let (_, (_, warm_git)) =
5964 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap());
5965 assert_eq!(warm_git, 1);
5966
5967 push_remote_config(&bare, "trunk", "[graph]\ncandidates = 3\n");
5969 git(&repo, &["fetch", "origin"]);
5970 let (cfg, (_, moved_git)) =
5971 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
5972 assert_eq!(cfg.graph.implementers, 3);
5973 assert_eq!(moved_git, 2);
5974 let (cfg, (_, warm_after_move)) =
5975 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
5976 assert_eq!(cfg.graph.implementers, 3);
5977 assert_eq!(warm_after_move, 1);
5978
5979 git(&repo, &["pack-refs", "--all"]);
5981 let (cfg, (_, packed_warm)) =
5982 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
5983 assert_eq!(cfg.graph.implementers, 3);
5984 assert_eq!(packed_warm, 1);
5985
5986 push_remote_config(&bare, "trunk", "[graph]\ncandidates = 4\n");
5988 git(&repo, &["fetch", "origin"]);
5989 git(&repo, &["pack-refs", "--all"]);
5990 let (cfg, (_, packed_move)) =
5991 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
5992 assert_eq!(cfg.graph.implementers, 4);
5993 assert_eq!(packed_move, 2);
5994 let (cfg, (_, packed_warm_2)) =
5995 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
5996 assert_eq!(cfg.graph.implementers, 4);
5997 assert_eq!(packed_warm_2, 1);
5998
5999 assert!(
6001 std::fs::read_to_string(repo.join("magi.toml"))
6002 .unwrap()
6003 .contains("candidates = 9")
6004 );
6005 }
6006
6007 #[test]
6008 fn linked_worktree_reuses_common_dir_cache_with_one_warm_git_spawn() {
6009 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
6010 let bare = t.path().join("o.git");
6011 let wt = t.path().join("linked-wt");
6012 git(
6013 &repo,
6014 &["worktree", "add", "--detach", &wt.to_string_lossy()],
6015 );
6016
6017 let (cfg, (_, cold_git)) =
6018 crate::web::request_cost::measure_sync(|| Config::discover(&wt, None).unwrap().0);
6019 assert_eq!(cfg.graph.implementers, 2);
6020 assert_eq!(cold_git, 2);
6021
6022 let (values, (_, warm_git)) = crate::web::request_cost::measure_sync(|| {
6023 (0..10)
6024 .map(|_| Config::discover(&wt, None).unwrap().0.graph.implementers)
6025 .collect::<Vec<_>>()
6026 });
6027 assert!(values.iter().all(|&n| n == 2));
6028 assert_eq!(warm_git, 10);
6029
6030 push_remote_config(&bare, "trunk", "[graph]\ncandidates = 5\n");
6031 git(&wt, &["fetch", "origin"]);
6032 let (cfg, (_, moved_git)) =
6033 crate::web::request_cost::measure_sync(|| Config::discover(&wt, None).unwrap().0);
6034 assert_eq!(cfg.graph.implementers, 5);
6035 assert_eq!(moved_git, 2);
6036 }
6037
6038 #[test]
6039 fn deleted_or_retargeted_refs_never_reuse_stale_cache() {
6040 let (t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
6041 let bare = t.path().join("o.git");
6042 assert_eq!(
6043 Config::discover(&repo, None).unwrap().0.graph.implementers,
6044 2
6045 );
6046
6047 git(&repo, &["update-ref", "-d", "refs/remotes/origin/trunk"]);
6049 assert!(Config::discover(&repo, None).is_err());
6050
6051 git(&repo, &["fetch", "origin"]);
6054 git(&repo, &["checkout", "-b", "alt"]);
6055 std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 6\n").unwrap();
6056 git(&repo, &["add", "magi.toml"]);
6057 git(&repo, &["commit", "-m", "alt"]);
6058 git(&repo, &["push", "origin", "alt"]);
6059 git(&repo, &["fetch", "origin"]);
6060 let _ = bare;
6061 git(&repo, &["remote", "set-head", "origin", "alt"]);
6062 assert_eq!(
6063 Config::discover(&repo, None).unwrap().0.graph.implementers,
6064 6
6065 );
6066
6067 git(&repo, &["remote", "set-head", "origin", "-d"]);
6069 assert!(Config::discover(&repo, None).is_err());
6070 }
6071
6072 #[test]
6073 fn include_repository_reuses_extracted_tree_with_one_warm_git_spawn() {
6074 let (_t, repo) = fixture("include = [\"gate.toml\"]\n", "");
6075 std::fs::write(repo.join("magi.toml"), "include = [\"gate.toml\"]\n").unwrap();
6076 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 2\n").unwrap();
6077 git(&repo, &["add", "-A"]);
6078 git(&repo, &["commit", "-m", "inc"]);
6079 git(&repo, &["push", "origin", "trunk"]);
6080 git(&repo, &["fetch", "origin"]);
6081 std::fs::write(repo.join("gate.toml"), "[graph]\ncandidates = 9\n").unwrap();
6082
6083 let (cfg, (_, cold_git)) =
6084 crate::web::request_cost::measure_sync(|| Config::discover(&repo, None).unwrap().0);
6085 assert_eq!(cfg.graph.implementers, 2);
6086 assert_eq!(cold_git, 3);
6088
6089 let (values, (_, warm_git)) = crate::web::request_cost::measure_sync(|| {
6090 (0..10)
6091 .map(|_| Config::discover(&repo, None).unwrap().0.graph.implementers)
6092 .collect::<Vec<_>>()
6093 });
6094 assert!(values.iter().all(|&n| n == 2));
6095 assert_eq!(warm_git, 10);
6096 }
6097
6098 #[test]
6099 fn partial_clone_loads_promised_config_blob() {
6100 let (tmp, source) = fixture("[graph]\ncandidates = 2\n", "");
6101 let bare = tmp.path().join("o.git");
6102 git(&bare, &["config", "uploadpack.allowFilter", "true"]);
6103 let clone = tmp.path().join("partial");
6104 git(
6105 tmp.path(),
6106 &[
6107 "clone",
6108 "--no-local",
6109 "--no-checkout",
6110 "--filter=blob:none",
6111 &bare.to_string_lossy(),
6112 &clone.to_string_lossy(),
6113 ],
6114 );
6115 let oid = git_out(&source, &["rev-parse", "HEAD:magi.toml"]).unwrap();
6116 let missing = repository_git()
6117 .env("GIT_NO_LAZY_FETCH", "1")
6118 .args(["cat-file", "-e", oid.trim()])
6119 .current_dir(&clone)
6120 .output()
6121 .unwrap();
6122 assert!(!missing.status.success(), "fixture must omit the blob");
6123 assert_eq!(
6124 Config::discover(&clone, None).unwrap().0.graph.implementers,
6125 2
6126 );
6127 }
6128
6129 #[test]
6130 fn missing_config_blob_is_not_cached_as_an_absent_layer() {
6131 let (_tmp, repo) = fixture("[graph]\ncandidates = 2\n", "");
6132 let oid = git_out(&repo, &["rev-parse", "HEAD:magi.toml"]).unwrap();
6133 let oid = oid.trim();
6134 let blob = repo.join(".git/objects").join(&oid[..2]).join(&oid[2..]);
6135 let saved = blob.with_extension("saved");
6136 std::fs::rename(&blob, &saved).unwrap();
6137 assert!(Config::discover(&repo, None).is_err());
6138 std::fs::rename(saved, blob).unwrap();
6139 assert_eq!(
6140 Config::discover(&repo, None).unwrap().0.graph.implementers,
6141 2
6142 );
6143 }
6144
6145 #[test]
6146 fn a_cached_config_does_not_hide_a_missing_base_commit() {
6147 let (_tmp, repo) = fixture("[graph]\ncandidates = 2\n", "");
6148 assert_eq!(
6149 Config::discover(&repo, None).unwrap().0.graph.implementers,
6150 2
6151 );
6152 let oid = git_out(&repo, &["rev-parse", "HEAD"]).unwrap();
6153 let oid = oid.trim();
6154 let commit = repo.join(".git/objects").join(&oid[..2]).join(&oid[2..]);
6155 let saved = commit.with_extension("saved");
6156 std::fs::rename(&commit, &saved).unwrap();
6157 assert!(Config::discover(&repo, None).is_err());
6158 std::fs::rename(saved, commit).unwrap();
6159 assert_eq!(
6160 Config::discover(&repo, None).unwrap().0.graph.implementers,
6161 2
6162 );
6163 }
6164
6165 #[test]
6166 fn corrupt_cache_directory_without_manifest_is_not_trusted() {
6167 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
6168 let sha = git_out(&repo, &["rev-parse", "refs/remotes/origin/trunk^{commit}"])
6169 .unwrap()
6170 .trim()
6171 .to_owned();
6172 let key = format!(
6173 "{sha}-{}-v{CACHE_MANIFEST_VERSION}",
6174 fnv_hex(&repo.to_string_lossy())
6175 );
6176 let bad_dir = repo.join(".git/magi/config").join(&key);
6177 std::fs::create_dir_all(&bad_dir).unwrap();
6178 std::fs::write(bad_dir.join("magi.toml"), "[graph]\ncandidates = 9\n").unwrap();
6179 std::fs::write(bad_dir.join(REPO_MARKER), repo.to_string_lossy().as_bytes()).unwrap();
6180
6181 let (cfg, _) = Config::discover(&repo, None).unwrap();
6183 assert_eq!(cfg.graph.implementers, 2);
6184 }
6185
6186 #[test]
6187 fn resolve_remote_head_and_commit_cli_uses_one_git_process() {
6188 let (_t, repo) = fixture("[graph]\ncandidates = 2\n", "[graph]\ncandidates = 9\n");
6189 let expected = git_out(&repo, &["rev-parse", "refs/remotes/origin/trunk^{commit}"])
6190 .unwrap()
6191 .trim()
6192 .to_owned();
6193 let (resolved, (_, git_calls)) = crate::web::request_cost::measure_sync(|| {
6194 resolve_remote_head_and_commit_cli(&repo, "origin").unwrap()
6195 });
6196 assert_eq!(resolved, ("trunk".to_owned(), expected));
6197 assert_eq!(git_calls, 1);
6198 }
6199
6200 #[test]
6201 fn standard_files_ref_backend_rejects_nonstandard_git_config() {
6202 let tmp = tempfile::tempdir().unwrap();
6203 let common = tmp.path().join("git");
6204 std::fs::create_dir_all(common.join("refs")).unwrap();
6205
6206 let check = |cfg: &str| {
6207 std::fs::write(common.join("config"), cfg).unwrap();
6208 is_standard_files_ref_backend(&common)
6209 };
6210
6211 assert!(check("[core]\n\trepositoryformatversion = 0\n"));
6212 assert!(check(
6213 "[core]\n\trepositoryformatversion = 1\n[extensions]\n\tworktreeConfig = true\n\trefStorage = files\n\tobjectFormat = sha1\n"
6214 ));
6215 assert!(!check(
6216 "[core]\n\trepositoryformatversion = 1\n[extensions]\n\trefStorage = reftable\n"
6217 ));
6218 assert!(!check(
6219 "[core]\n\trepositoryformatversion = 1\n[extensions]\n\tobjectFormat = sha256\n"
6220 ));
6221 assert!(!check(
6222 "[core]\n\trepositoryformatversion = 1\n[extensions]\n\tunknownExt\n"
6223 ));
6224 assert!(!check(
6225 "[core]\n\trepositoryformatversion = 1\n[extensions] refStorage = reftable\n"
6226 ));
6227 assert!(!check(
6228 "[core]\n\trepositoryformatversion = 0\n[include]\n\tpath = extra.cfg\n"
6229 ));
6230 assert!(!check(
6231 "[core]\n\trepositoryformatversion = 0\n\tfoo = bar\\\nbaz\n"
6232 ));
6233 }
6234 }
6235
6236 #[test]
6237 fn github_language_defaults_to_english_and_accepts_japanese() {
6238 let default: Graph = toml::from_str("").unwrap();
6239 assert_eq!(default.github_language, "en");
6240 assert!(default.github_english() && default.language_gate());
6241 let ja: Graph = toml::from_str("github_language = \"ja\"").unwrap();
6242 assert!(!ja.github_english() && !ja.language_gate());
6243 let only_ops: Graph = toml::from_str("language = \"ja\"").unwrap();
6245 assert!(only_ops.language_gate());
6246 let off: Graph = toml::from_str("github_text_guard = false").unwrap();
6247 assert!(!off.language_gate() && off.github_english());
6248 assert!(Config::starter_toml().contains("github_language = \"en\""));
6249 }
6250}