1use std::collections::BTreeMap;
32use std::path::{Path, PathBuf};
33use std::sync::Mutex;
34
35use serde::Serialize;
36
37use crate::config::{AgentChoice, AgentSpec, Config};
38
39pub(crate) const ROLE_KEYS: [&str; 10] = [
41 "implementers",
42 "judges",
43 "reviewers",
44 "advisors",
45 "synthesizer",
46 "fixer",
47 "chatter",
48 "conductor",
49 "language_judge",
50 "dupes_judge",
51];
52
53fn is_chain_role(key: &str) -> bool {
55 matches!(
56 key,
57 "synthesizer" | "fixer" | "chatter" | "conductor" | "language_judge" | "dupes_judge"
58 )
59}
60
61static SAVE_LOCK: Mutex<()> = Mutex::new(());
63
64#[derive(Debug, Serialize)]
66pub(crate) struct SettingsView {
67 pub(crate) repo: String,
69 pub(crate) machine: MachineView,
70 pub(crate) repositories: Vec<crate::repos::Repo>,
71 pub(crate) revision: String,
73 pub(crate) error: Option<ConfigError>,
76 pub(crate) roles: Vec<RoleView>,
77 pub(crate) agents: Vec<AgentView>,
78}
79
80#[derive(Debug, Serialize)]
81pub(crate) struct MachineView {
82 pub(crate) path: Option<String>,
84 pub(crate) exists: bool,
85 pub(crate) unavailable: Option<String>,
87}
88
89#[derive(Debug, Serialize)]
90pub(crate) struct ConfigError {
91 pub(crate) message: String,
92 pub(crate) path: Option<String>,
94}
95
96#[derive(Debug, Serialize)]
97pub(crate) struct RoleView {
98 pub(crate) key: &'static str,
99 pub(crate) chain: bool,
101 pub(crate) configured: Vec<String>,
103 pub(crate) source: &'static str,
105 pub(crate) source_path: Option<String>,
106 pub(crate) machine_value: Option<toml::Value>,
108 pub(crate) editable: bool,
110 pub(crate) locked_reason: Option<String>,
111 pub(crate) fallback: Option<&'static str>,
113 pub(crate) seats: Vec<String>,
115 pub(crate) seats_error: Option<String>,
116 pub(crate) skipped: Vec<String>,
118 pub(crate) count: Option<CountView>,
120}
121
122#[derive(Debug, Serialize)]
126pub(crate) struct CountView {
127 pub(crate) value: usize,
128 pub(crate) min: usize,
131 pub(crate) file_key: &'static str,
134 pub(crate) source: &'static str,
136 pub(crate) source_path: Option<String>,
137 pub(crate) machine_value: Option<toml::Value>,
139 pub(crate) editable: bool,
140 pub(crate) locked_reason: Option<String>,
141 pub(crate) roster_len: Option<usize>,
143 pub(crate) backups: Option<usize>,
145}
146
147const COUNT_KEYS: [&str; 4] = ["implementers", "judges", "reviewers", "advisors"];
149
150fn count_spellings(key: &str) -> &'static [&'static str] {
151 match key {
152 "implementers" => &["implementers", "candidates"],
153 "judges" => &["judges"],
154 "reviewers" => &["reviewers"],
155 _ => &["advisors"],
156 }
157}
158
159fn count_min(key: &str) -> usize {
160 usize::from(key != "advisors")
161}
162
163fn graph_count(cfg: &Config, key: &str) -> usize {
164 match key {
165 "implementers" => cfg.graph.implementers,
166 "judges" => cfg.graph.judges,
167 "reviewers" => cfg.graph.reviewers,
168 _ => cfg.graph.advisors,
169 }
170}
171
172fn declares_count(table: &toml::Table, key: &str) -> bool {
173 table
174 .get("graph")
175 .and_then(toml::Value::as_table)
176 .is_some_and(|g| count_spellings(key).iter().any(|k| g.contains_key(*k)))
177}
178
179#[derive(Debug, Serialize)]
180pub(crate) struct AgentView {
181 pub(crate) id: String,
182 pub(crate) kind: String,
183 pub(crate) model: Option<String>,
184 pub(crate) source: &'static str,
186 pub(crate) source_path: Option<String>,
187}
188
189#[derive(Debug)]
191pub(crate) enum SaveError {
192 Conflict(String),
194 Refused(String),
196 Internal(String),
198}
199
200fn fingerprint(bytes: &[u8]) -> String {
202 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
203 for b in bytes {
204 hash ^= u64::from(*b);
205 hash = hash.wrapping_mul(0x0100_0000_01b3);
206 }
207 format!("{hash:016x}")
208}
209
210fn repo_layers(repo: &Path) -> Vec<PathBuf> {
211 Config::repo_layers(repo).unwrap_or_else(|e| {
212 tracing::warn!("could not read the repository's config layers: {e:#}");
213 Vec::new()
214 })
215}
216
217fn layer_paths_strict(repo: &Path, machine: Option<&Path>) -> anyhow::Result<Vec<PathBuf>> {
221 let mut paths: Vec<PathBuf> = machine
222 .filter(|m| m.is_file())
223 .map(Path::to_path_buf)
224 .into_iter()
225 .collect();
226 paths.extend(Config::repo_layers(repo)?);
227 Ok(paths)
228}
229
230#[cfg(test)]
234fn layer_paths(repo: &Path, machine: Option<&Path>) -> Vec<PathBuf> {
235 let mut paths: Vec<PathBuf> = machine
236 .filter(|m| m.is_file())
237 .map(Path::to_path_buf)
238 .into_iter()
239 .collect();
240 paths.extend(repo_layers(repo));
241 paths
242}
243
244fn effective(paths: &[PathBuf]) -> anyhow::Result<Config> {
245 if paths.is_empty() {
246 return Ok(Config::autodetected());
247 }
248 Config::load_layers(paths)
249}
250
251fn declares(table: &toml::Table, key: &str) -> bool {
252 table
253 .get("roles")
254 .and_then(toml::Value::as_table)
255 .is_some_and(|r| r.contains_key(key))
256}
257
258fn key_name(key: &str) -> &'static str {
259 COUNT_KEYS
260 .iter()
261 .find(|k| **k == key)
262 .copied()
263 .unwrap_or("")
264}
265
266fn choice_ids(choice: Option<&AgentChoice>) -> Vec<String> {
267 choice
268 .map(|c| c.ids().into_iter().map(str::to_owned).collect())
269 .unwrap_or_default()
270}
271
272fn role_ids(cfg: &Config, key: &str) -> Vec<String> {
273 match key {
274 "implementers" => cfg.roles.implementers.clone(),
275 "judges" => cfg.roles.judges.clone(),
276 "reviewers" => cfg.roles.reviewers.clone(),
277 "advisors" => cfg.roles.advisors.clone(),
278 key if is_chain_role(key) => choice_ids(chain_choice(cfg, key)),
279 _ => unreachable!("unknown settings role: {key}"),
280 }
281}
282
283fn chain_choice<'a>(cfg: &'a Config, key: &str) -> Option<&'a AgentChoice> {
284 match key {
285 "synthesizer" => cfg.roles.synthesizer.as_ref(),
286 "fixer" => cfg.roles.fixer.as_ref(),
287 "chatter" => cfg.roles.chatter.as_ref(),
288 "conductor" => cfg.roles.conductor.as_ref(),
289 "language_judge" => cfg.roles.language_judge.as_ref(),
290 "dupes_judge" => cfg.roles.dupes_judge.as_ref(),
291 _ => unreachable!("unknown chain role: {key}"),
292 }
293}
294
295fn chain_seats(
296 cfg: &Config,
297 choice: Option<&AgentChoice>,
298 view: &mut RoleView,
299) -> anyhow::Result<Vec<String>> {
300 let seats = crate::agent::pick_chain(&cfg.agents, choice, &crate::agent::installed, view.key)
301 .map(|chain| ids_of(&chain));
302 let runnable = seats.as_ref().cloned().unwrap_or_default();
303 view.skipped = choice_ids(choice)
304 .into_iter()
305 .filter(|id| !runnable.contains(id))
306 .collect();
307 seats
308}
309
310fn ids_of(specs: &[AgentSpec]) -> Vec<String> {
311 specs.iter().map(|s| s.id.clone()).collect()
312}
313
314#[cfg(test)]
317pub(crate) fn view(repo: &Path, machine: Option<&Path>) -> SettingsView {
318 view_with_repos(repo, machine, &[])
319}
320
321pub(crate) fn repository_config(repo: &Path, machine: Option<&Path>) -> anyhow::Result<Config> {
322 effective(&layer_paths_strict(repo, machine)?)
323}
324
325pub(crate) fn view_with_repos(
326 repo: &Path,
327 machine: Option<&Path>,
328 known: &[crate::repos::Repo],
329) -> SettingsView {
330 let bytes = machine
331 .and_then(|m| std::fs::read(m).ok())
332 .unwrap_or_default();
333 let mut out = SettingsView {
334 repo: repo.display().to_string(),
335 machine: MachineView {
336 path: machine.map(|m| m.display().to_string()),
337 exists: machine.is_some_and(Path::is_file),
338 unavailable: machine.is_none().then(|| {
339 "This machine has no machine-config location (the config directory is \
340 unset or empty), so nothing can be saved from here."
341 .to_owned()
342 }),
343 },
344 repositories: known.to_vec(),
345 revision: fingerprint(&bytes),
346 error: None,
347 roles: Vec::new(),
348 agents: Vec::new(),
349 };
350 let paths = match layer_paths_strict(repo, machine) {
351 Ok(p) => p,
352 Err(e) => {
353 out.error = Some(ConfigError {
354 message: format!("{e:#}"),
355 path: None,
356 });
357 return out;
358 }
359 };
360 let cfg = match effective(&paths) {
361 Ok(cfg) => cfg,
362 Err(e) => {
363 let failing = Config::layer_tables(&paths)
364 .into_iter()
365 .find(|(_, t)| t.is_err())
366 .map(|(p, _)| p.display().to_string());
367 out.error = Some(ConfigError {
368 message: format!("{e:#}"),
369 path: failing,
370 });
371 return out;
372 }
373 };
374 let tables: Vec<(PathBuf, toml::Table)> = Config::layer_tables(&paths)
375 .into_iter()
376 .filter_map(|(p, t)| t.ok().map(|t| (p, t)))
377 .collect();
378 let is_machine = |p: &Path| machine.is_some_and(|m| m == p);
379
380 let mut other_declares: BTreeMap<&str, String> = BTreeMap::new();
381 for (other, layers) in other_checkouts(repo, &cfg.repos.roots, known) {
382 let theirs = Config::layer_tables(&layers);
383 for key in ROLE_KEYS {
384 if theirs
385 .iter()
386 .any(|(_, t)| t.as_ref().is_ok_and(|t| declares(t, key)))
387 {
388 other_declares
389 .entry(key)
390 .or_insert_with(|| other.name.clone());
391 }
392 }
393 }
394 let resolved = cfg.resolve_roles();
395 let advisors = cfg.advisors();
396 for key in ROLE_KEYS {
397 let configured = role_ids(&cfg, key);
398 let owner = tables.iter().rev().find(|(_, t)| declares(t, key));
399 let (source, source_path) = match owner {
400 Some((p, _)) if is_machine(p) => ("machine", Some(p.display().to_string())),
401 Some((p, _)) => ("repo", Some(Config::repo_layer_description(repo, p))),
402 None => ("default", None),
403 };
404 let repo_owner = tables
405 .iter()
406 .find(|(p, t)| !is_machine(p) && declares(t, key));
407 let (editable, locked_reason) = if let Some((p, _)) = repo_owner {
408 (
409 false,
410 Some(format!(
411 "This repo overrides roles.{key} in {} - edit it there.",
412 Config::repo_layer_description(repo, p)
413 )),
414 )
415 } else if let Some(name) = other_declares.get(key) {
416 (
417 false,
418 Some(format!(
419 "`{name}` declares roles.{key} in its own config, so a machine setting \
420 would stop it from loading. Edit it there."
421 )),
422 )
423 } else if machine.is_none() {
424 (false, out.machine.unavailable.clone())
425 } else {
426 (true, None)
427 };
428 let mut view = RoleView {
429 key,
430 chain: is_chain_role(key),
431 configured,
432 source,
433 source_path,
434 machine_value: tables
435 .iter()
436 .find(|(p, _)| is_machine(p))
437 .and_then(|(_, t)| t.get("roles")?.get(key))
438 .cloned(),
439 editable,
440 locked_reason,
441 fallback: None,
442 seats: Vec::new(),
443 seats_error: None,
444 skipped: Vec::new(),
445 count: None,
446 };
447 if COUNT_KEYS.contains(&key) {
448 let owner = tables.iter().rev().find(|(_, t)| declares_count(t, key));
449 let (source, source_path) = match owner {
450 Some((p, _)) if is_machine(p) => ("machine", Some(p.display().to_string())),
451 Some((p, _)) => ("repo", Some(Config::repo_layer_description(repo, p))),
452 None => ("default", None),
453 };
454 let repo_owner = tables
455 .iter()
456 .find(|(p, t)| !is_machine(p) && declares_count(t, key));
457 let (editable, locked_reason) = if let Some((p, _)) = repo_owner {
458 (
459 false,
460 Some(format!(
461 "This repo overrides graph.{key} in {} - edit it there.",
462 Config::repo_layer_description(repo, p)
463 )),
464 )
465 } else if machine.is_none() {
466 (false, out.machine.unavailable.clone())
467 } else {
468 (true, None)
469 };
470 let file_key = tables
471 .iter()
472 .find(|(p, _)| is_machine(p))
473 .and_then(|(_, t)| t.get("graph").and_then(toml::Value::as_table))
474 .filter(|g| key == "implementers" && g.contains_key("candidates"))
475 .map_or(key_name(key), |_| "candidates");
476 let roster_len = resolved.as_ref().ok().map(|r| match key {
477 "implementers" => r.implementer_roster.len(),
478 "judges" => r.judge_roster.len(),
479 _ => r.reviewer_roster.len(),
480 });
481 let roster_len = if key == "advisors" {
482 cfg.advisor_roster().ok().map(|r| r.len())
483 } else {
484 roster_len
485 };
486 let value = graph_count(&cfg, key);
487 view.count = Some(CountView {
488 value,
489 min: count_min(key),
490 file_key,
491 source,
492 source_path,
493 machine_value: tables
494 .iter()
495 .find(|(p, _)| is_machine(p))
496 .and_then(|(_, t)| {
497 count_spellings(key)
498 .iter()
499 .find_map(|k| t.get("graph")?.get(*k))
500 })
501 .cloned(),
502 editable,
503 locked_reason,
504 roster_len,
505 backups: roster_len.map(|n| n.saturating_sub(value)),
506 });
507 }
508 let seats = match key {
509 "implementers" => resolved
510 .as_ref()
511 .map(|r| ids_of(&r.implementers))
512 .map_err(|e| anyhow::anyhow!("{e:#}")),
513 "judges" => resolved
514 .as_ref()
515 .map(|r| ids_of(&r.judges))
516 .map_err(|e| anyhow::anyhow!("{e:#}")),
517 "reviewers" => resolved
518 .as_ref()
519 .map(|r| ids_of(&r.reviewers))
520 .map_err(|e| anyhow::anyhow!("{e:#}")),
521 "advisors" => {
522 if view.configured.is_empty() {
523 view.fallback = Some("judges");
524 }
525 advisors
526 .as_ref()
527 .map(|a| ids_of(a))
528 .map_err(|e| anyhow::anyhow!("{e:#}"))
529 }
530 "fixer" if cfg.roles.fixer.is_none() => {
532 view.fallback = Some("winner's implementer");
533 Ok(Vec::new())
534 }
535 "language_judge" if cfg.roles.language_judge.is_none() => {
536 view.fallback = Some("built-in heuristics");
537 Ok(Vec::new())
538 }
539 "dupes_judge" => {
540 if cfg.roles.dupes_judge.is_none() {
541 view.fallback = Some("chatter");
542 }
543 chain_seats(
544 &cfg,
545 cfg.roles
546 .dupes_judge
547 .as_ref()
548 .or(cfg.roles.chatter.as_ref()),
549 &mut view,
550 )
551 }
552 "conductor"
554 if cfg
555 .roles
556 .conductor
557 .as_ref()
558 .is_none_or(|c| c.ids().len() <= 1) =>
559 {
560 let seats = resolved
561 .as_ref()
562 .map(|r| vec![r.conductor.id.clone()])
563 .map_err(|e| anyhow::anyhow!("{e:#}"));
564 if seats.is_err() {
565 view.skipped = view.configured.clone();
566 }
567 seats
568 }
569 "fixer" | "synthesizer" | "chatter" | "conductor" | "language_judge" => {
570 chain_seats(&cfg, chain_choice(&cfg, key), &mut view)
571 }
572 _ => unreachable!("unknown settings role: {key}"),
573 };
574 match seats {
575 Ok(ids) => view.seats = ids,
576 Err(e) => view.seats_error = Some(format!("{e:#}")),
577 }
578 out.roles.push(view);
579 }
580
581 out.agents = cfg
582 .agents
583 .iter()
584 .map(|a| {
585 let owner = tables.iter().rev().find(|(_, t)| {
586 t.get("agents")
587 .and_then(toml::Value::as_array)
588 .is_some_and(|list| {
589 list.iter()
590 .any(|x| x.get("id").and_then(toml::Value::as_str) == Some(&a.id))
591 })
592 });
593 let (source, source_path) = match owner {
594 Some((p, _)) if is_machine(p) => ("machine", Some(p.display().to_string())),
595 Some((p, _)) => ("repo", Some(Config::repo_layer_description(repo, p))),
596 None => ("detected", None),
597 };
598 AgentView {
599 id: a.id.clone(),
600 kind: toml::Value::try_from(a.kind)
601 .ok()
602 .and_then(|v| v.as_str().map(str::to_owned))
603 .unwrap_or_default(),
604 model: a.model.clone(),
605 source,
606 source_path,
607 }
608 })
609 .collect();
610 out
611}
612
613#[cfg(test)]
618pub(crate) fn save(
619 repo: &Path,
620 machine: Option<&Path>,
621 revision: &str,
622 roles: &BTreeMap<String, Vec<String>>,
623 counts: &BTreeMap<String, serde_json::Value>,
624) -> Result<SettingsView, SaveError> {
625 save_with_repos(repo, machine, revision, roles, counts, &[])
626}
627
628pub(crate) fn save_with_repos(
629 repo: &Path,
630 machine: Option<&Path>,
631 revision: &str,
632 roles: &BTreeMap<String, Vec<String>>,
633 counts: &BTreeMap<String, serde_json::Value>,
634 known: &[crate::repos::Repo],
635) -> Result<SettingsView, SaveError> {
636 let _guard = SAVE_LOCK.lock().unwrap_or_else(|p| p.into_inner());
637 let Some(machine) = machine else {
638 return Err(SaveError::Refused(
639 "This machine has no machine-config location, so there is nowhere to save to."
640 .to_owned(),
641 ));
642 };
643 let current = view_with_repos(repo, Some(machine), known);
644 if let Some(err) = ¤t.error {
645 return Err(SaveError::Refused(format!(
646 "The current config does not load, so it cannot be edited safely: {}",
647 err.message
648 )));
649 }
650 if current.revision != revision {
651 return Err(SaveError::Conflict(
652 "The machine config changed since this screen loaded it. Reload and apply \
653 the change again."
654 .to_owned(),
655 ));
656 }
657 if roles.is_empty() && counts.is_empty() {
658 return Err(SaveError::Refused("Nothing to change.".to_owned()));
659 }
660 let agent_ids: Vec<&str> = current.agents.iter().map(|a| a.id.as_str()).collect();
661 let mut edits: Vec<(&'static str, Vec<String>)> = Vec::new();
662 for (key, ids) in roles {
663 let Some(role) = current.roles.iter().find(|r| r.key == key) else {
664 return Err(SaveError::Refused(format!(
665 "`{key}` is not a role this screen edits."
666 )));
667 };
668 if !role.editable {
669 return Err(SaveError::Refused(
670 role.locked_reason
671 .clone()
672 .unwrap_or_else(|| format!("`{key}` cannot be edited here.")),
673 ));
674 }
675 let ids: Vec<String> = ids.iter().map(|i| i.trim().to_owned()).collect();
676 if let Some(bad) = ids
677 .iter()
678 .find(|i| i.is_empty() || !agent_ids.contains(&i.as_str()))
679 {
680 return Err(SaveError::Refused(format!(
681 "`{bad}` is not a defined agent. Defined: {}.",
682 agent_ids.join(", ")
683 )));
684 }
685 edits.push((role.key, ids));
686 }
687 let mut count_edits: Vec<(&'static str, &'static str, usize)> = Vec::new();
688 for (key, raw) in counts {
689 let Some(count) = current
690 .roles
691 .iter()
692 .find(|r| r.key == key)
693 .and_then(|r| r.count.as_ref())
694 else {
695 return Err(SaveError::Refused(format!(
696 "`{key}` has no seat count this screen edits."
697 )));
698 };
699 if !count.editable {
700 return Err(SaveError::Refused(
701 count
702 .locked_reason
703 .clone()
704 .unwrap_or_else(|| format!("The `{key}` seat count cannot be edited here.")),
705 ));
706 }
707 let Some(n) = raw.as_u64().and_then(|n| usize::try_from(n).ok()) else {
708 return Err(SaveError::Refused(format!(
709 "The {key} seat count must be a whole number, got {raw}."
710 )));
711 };
712 if n < count.min {
713 return Err(SaveError::Refused(format!(
714 "The {key} seat count must be at least {}, got {n}.",
715 count.min
716 )));
717 }
718 count_edits.push((key_name(key), count.file_key, n));
719 }
720
721 let original = match std::fs::read_to_string(machine) {
722 Ok(text) => text,
723 Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
724 Err(e) => {
725 return Err(SaveError::Internal(format!(
726 "reading {}: {e}",
727 machine.display()
728 )));
729 }
730 };
731 let mut text = original.clone();
732 for (key, ids) in &edits {
733 text = patch_role(&text, key, ids).map_err(SaveError::Refused)?;
734 }
735 for (key, file_key, n) in &count_edits {
736 text = patch_count(&text, file_key, key, *n).map_err(SaveError::Refused)?;
737 }
738 let dir = machine
739 .parent()
740 .ok_or_else(|| SaveError::Internal("the machine config has no parent directory".into()))?;
741 std::fs::create_dir_all(dir)
742 .map_err(|e| SaveError::Internal(format!("creating {}: {e}", dir.display())))?;
743 let nonce = std::time::SystemTime::now()
744 .duration_since(std::time::UNIX_EPOCH)
745 .map_or(0, |d| d.as_nanos());
746 let tmp = dir.join(format!(".config.toml.{}.{nonce}.tmp", std::process::id()));
747 let cleanup = |e: SaveError| {
748 let _ = std::fs::remove_file(&tmp);
749 e
750 };
751 write_synced(&tmp, &text).map_err(|e| {
752 cleanup(SaveError::Internal(format!(
753 "writing {}: {e}",
754 tmp.display()
755 )))
756 })?;
757
758 let mut layers = vec![tmp.clone()];
761 match Config::repo_layers(repo) {
762 Ok(l) => layers.extend(l),
763 Err(e) => {
764 return Err(cleanup(SaveError::Refused(format!(
765 "The repository's config cannot be read, so nothing was saved: {e:#}"
766 ))));
767 }
768 }
769 let loaded = Config::load_layers(&layers).map_err(|e| {
770 cleanup(SaveError::Refused(format!(
771 "The change would leave the config unloadable, so nothing was saved: {e:#}"
772 )))
773 })?;
774 for (key, ids) in &edits {
775 let got = role_ids(&loaded, key);
776 if &got != ids {
777 return Err(cleanup(SaveError::Refused(format!(
778 "The change would not take effect as asked: `{key}` would resolve to [{}] \
779 instead of [{}] (an include or a template in the machine file overrides \
780 it). Nothing was saved.",
781 got.join(", "),
782 ids.join(", ")
783 ))));
784 }
785 }
786 for (key, _, n) in &count_edits {
787 let got = graph_count(&loaded, key);
788 if got != *n {
789 return Err(cleanup(SaveError::Refused(format!(
790 "The change would not take effect as asked: the {key} seat count would be \
791 {got} instead of {n} (an include or a template in the machine file \
792 overrides it). Nothing was saved."
793 ))));
794 }
795 }
796 other_repos_still_load(repo, machine, &tmp, &loaded.repos.roots, known).map_err(cleanup)?;
797 std::fs::rename(&tmp, machine).map_err(|e| {
798 cleanup(SaveError::Internal(format!(
799 "replacing {}: {e}",
800 machine.display()
801 )))
802 })?;
803 Ok(view_with_repos(repo, Some(machine), known))
804}
805
806fn other_checkouts(
809 repo: &Path,
810 roots: &[PathBuf],
811 known: &[crate::repos::Repo],
812) -> Vec<(crate::repos::Repo, Vec<PathBuf>)> {
813 let here = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
814 let mut checkouts = crate::repos::scan(roots);
815 for r in known {
816 if !checkouts.iter().any(|c| c.path == r.path) {
817 checkouts.push(r.clone());
818 }
819 }
820 checkouts
821 .into_iter()
822 .filter(|r| r.path != here)
823 .filter_map(|r| {
824 let layers = repo_layers(&r.path);
825 (!layers.is_empty()).then_some((r, layers))
826 })
827 .collect()
828}
829
830fn other_repos_still_load(
836 repo: &Path,
837 machine: &Path,
838 proposal: &Path,
839 roots: &[PathBuf],
840 known: &[crate::repos::Repo],
841) -> Result<(), SaveError> {
842 let machine_exists = machine.is_file();
843 for (other, layers) in other_checkouts(repo, roots, known) {
844 let mut old: Vec<PathBuf> = if machine_exists {
845 vec![machine.to_path_buf()]
846 } else {
847 Vec::new()
848 };
849 old.extend(layers.iter().cloned());
850 if Config::load_layers(&old).is_err() {
851 continue;
852 }
853 let mut new = vec![proposal.to_path_buf()];
854 new.extend(layers);
855 if let Err(e) = Config::load_layers(&new) {
856 return Err(SaveError::Refused(format!(
857 "Nothing was saved: this machine setting would stop `{}` from loading, \
858 because that repository declares the same setting in its own config \
859 ({e:#}). Edit it there, or remove it from that repository first.",
860 other.name
861 )));
862 }
863 }
864 Ok(())
865}
866
867fn write_synced(path: &Path, text: &str) -> std::io::Result<()> {
868 use std::io::Write;
869 let mut f = std::fs::File::create(path)?;
870 f.write_all(text.as_bytes())?;
871 f.sync_all()
872}
873
874fn quote(s: &str) -> String {
875 toml::Value::String(s.to_owned()).to_string()
876}
877
878fn value_text(key: &str, ids: &[String]) -> String {
881 if is_chain_role(key) && ids.len() == 1 {
882 return quote(&ids[0]);
883 }
884 let items: Vec<String> = ids.iter().map(|i| quote(i)).collect();
885 format!("[{}]", items.join(", "))
886}
887
888#[derive(Default)]
891struct Scan {
892 depth: i32,
893 multi: Option<&'static str>,
894}
895
896impl Scan {
897 fn open(&self) -> bool {
898 self.depth > 0 || self.multi.is_some()
899 }
900}
901
902fn scan_line(line: &str, st: &mut Scan) -> Option<usize> {
906 let b = line.as_bytes();
907 let mut quote: Option<u8> = None;
908 let mut escaped = false;
909 let mut i = 0;
910 while i < b.len() {
911 if let Some(delim) = st.multi {
912 if b[i..].starts_with(delim.as_bytes()) {
913 st.multi = None;
914 i += 3;
915 } else if delim == "\"\"\"" && b[i] == b'\\' {
916 i += 2;
917 } else {
918 i += 1;
919 }
920 continue;
921 }
922 let c = b[i];
923 match quote {
924 Some(b'"') if escaped => escaped = false,
925 Some(b'"') if c == b'\\' => escaped = true,
926 Some(q) if c == q => quote = None,
927 Some(_) => {}
928 None => {
929 if b[i..].starts_with(b"\"\"\"") {
930 st.multi = Some("\"\"\"");
931 i += 3;
932 continue;
933 }
934 if b[i..].starts_with(b"'''") {
935 st.multi = Some("'''");
936 i += 3;
937 continue;
938 }
939 match c {
940 b'"' | b'\'' => quote = Some(c),
941 b'[' | b'{' => st.depth += 1,
942 b']' | b'}' => st.depth -= 1,
943 b'#' => return Some(i),
944 _ => {}
945 }
946 }
947 }
948 i += 1;
949 }
950 None
951}
952
953fn quoted_ids(code: &str) -> Vec<String> {
955 code.split('"')
956 .skip(1)
957 .step_by(2)
958 .map(str::to_owned)
959 .collect()
960}
961
962fn assigned_key(trimmed: &str) -> Option<(String, usize)> {
964 let eq = trimmed.find('=')?;
965 let raw = trimmed[..eq].trim();
966 let key = raw.trim_matches(|c| c == '"' || c == '\'');
967 let simple = !key.is_empty()
968 && key
969 .chars()
970 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
971 simple.then(|| (key.to_owned(), eq + 1))
972}
973
974fn is_roles_header(trimmed: &str) -> bool {
975 is_table_header(trimmed, "roles")
976}
977
978fn is_table_header(trimmed: &str, name: &str) -> bool {
979 let Some(rest) = trimmed.strip_prefix('[') else {
980 return false;
981 };
982 if rest.starts_with('[') {
983 return false;
984 }
985 rest.split(']')
986 .next()
987 .is_some_and(|n| n.trim().trim_matches(|c| c == '"' || c == '\'') == name)
988}
989
990struct OldSpan {
993 start: usize,
994 end: usize,
995 notes: Vec<(usize, Vec<String>, String)>,
997 seats: Vec<(String, Option<String>)>,
1001}
1002
1003fn patch_role(text: &str, key: &str, ids: &[String]) -> Result<String, String> {
1010 let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
1011 let lines: Vec<&str> = text.split_inclusive('\n').collect();
1012
1013 let mut st = Scan::default();
1016 let mut in_roles = false;
1017 let mut header: Option<usize> = None;
1018 let mut last_key_end: Option<usize> = None;
1019 let mut span: Option<OldSpan> = None;
1020 let mut i = 0;
1021 while i < lines.len() {
1022 let trimmed = lines[i].trim();
1023 if !st.open() && trimmed.starts_with('[') {
1024 in_roles = header.is_none() && is_roles_header(trimmed);
1025 if in_roles {
1026 header = Some(i);
1027 } else if header.is_some() {
1028 break;
1029 }
1030 i += 1;
1031 continue;
1032 }
1033 if !st.open()
1034 && let Some((name, _)) = assigned_key(trimmed)
1035 {
1036 let start = i;
1037 let first = lines[i].trim_start();
1038 let at = first.find('=').map_or(0, |p| p + 1);
1039 let mut end = i;
1040 let mut notes = Vec::new();
1041 let mut seats: Vec<(String, Option<String>)> = Vec::new();
1042 let mut note = |line: usize, code: &str, hash: Option<usize>| {
1043 let ids = quoted_ids(&code[..hash.unwrap_or(code.len())]);
1044 let comment = hash.map(|h| code[h..].trim_end().to_owned());
1045 let last = ids.len().saturating_sub(1);
1046 for (n, id) in ids.iter().enumerate() {
1047 seats.push((id.clone(), comment.clone().filter(|_| n == last)));
1048 }
1049 if let Some(c) = comment {
1050 notes.push((line, ids, c));
1051 }
1052 };
1053 let code = &first[at..];
1054 let hash = scan_line(code, &mut st);
1055 note(start, code, hash);
1056 while st.open() && end + 1 < lines.len() {
1057 end += 1;
1058 let hash = scan_line(lines[end], &mut st);
1059 note(end, lines[end], hash);
1060 }
1061 if in_roles {
1062 last_key_end = Some(end);
1063 if name == key {
1064 let body = lines[start..=end].concat();
1065 if body.contains("\"\"\"") || body.contains("'''") {
1066 return Err(format!(
1067 "`{key}` uses a multi-line string; edit it by hand."
1068 ));
1069 }
1070 if body.contains("{{") || body.contains("{%") {
1071 return Err(format!(
1072 "`{key}` is written with a template expression, which this screen \
1073 cannot edit without losing it. Change it by hand."
1074 ));
1075 }
1076 span = Some(OldSpan {
1077 start,
1078 end,
1079 notes,
1080 seats,
1081 });
1082 }
1083 }
1084 i = end + 1;
1085 continue;
1086 }
1087 if st.open() {
1088 scan_line(lines[i], &mut st);
1089 }
1090 i += 1;
1091 }
1092
1093 let mut out: Vec<String> = lines.iter().map(|l| (*l).to_owned()).collect();
1094 let new_line = |indent: &str, comment: Option<&str>| {
1095 let mut s = format!("{indent}{key} = {}", value_text(key, ids));
1096 if let Some(c) = comment {
1097 s.push_str(" ");
1098 s.push_str(c);
1099 }
1100 s.push_str(eol);
1101 s
1102 };
1103 match (span, ids.is_empty()) {
1104 (Some(old), true) => {
1105 let indent: String = lines[old.start]
1106 .chars()
1107 .take_while(|c| c.is_whitespace())
1108 .collect();
1109 let kept: Vec<String> = old
1110 .notes
1111 .iter()
1112 .map(|(_, _, c)| format!("{indent}{c}{eol}"))
1113 .collect();
1114 out.splice(old.start..=old.end, kept);
1115 }
1116 (Some(old), false) => {
1117 let indent: String = lines[old.start]
1118 .chars()
1119 .take_while(|c| c.is_whitespace())
1120 .collect();
1121 let single = old.start == old.end;
1122 let trailing = match old.notes.last() {
1125 Some((line, on_line, c)) if *line == old.end && (single || on_line.is_empty()) => {
1126 Some(c.clone())
1127 }
1128 _ => None,
1129 };
1130 let interior = &old.notes[..old.notes.len() - usize::from(trailing.is_some())];
1131 let replacement: Vec<String> =
1132 if interior.is_empty() || (is_chain_role(key) && ids.len() == 1) {
1133 let mut v: Vec<String> = interior
1135 .iter()
1136 .map(|(_, _, c)| format!("{indent}{c}{eol}"))
1137 .collect();
1138 v.push(new_line(&indent, trailing.as_deref()));
1139 v
1140 } else {
1141 let mut v = vec![format!("{indent}{key} = [{eol}")];
1142 for (_, _, c) in interior.iter().filter(|(_, l, _)| l.is_empty()) {
1143 v.push(format!("{indent} {c}{eol}"));
1144 }
1145 let mut taken: std::collections::HashMap<&str, usize> = Default::default();
1146 for id in ids {
1147 let nth = taken.entry(id.as_str()).or_insert(0);
1148 let note = old
1149 .seats
1150 .iter()
1151 .filter(|(old_id, _)| old_id == id)
1152 .nth(*nth)
1153 .and_then(|(_, c)| c.as_ref())
1154 .map(|c| format!(" {c}"))
1155 .unwrap_or_default();
1156 *nth += 1;
1157 v.push(format!("{indent} {},{note}{eol}", quote(id)));
1158 }
1159 v.push(format!(
1160 "{indent}]{}{eol}",
1161 trailing.map(|c| format!(" {c}")).unwrap_or_default()
1162 ));
1163 v
1164 };
1165 out.splice(old.start..=old.end, replacement);
1166 }
1167 (None, true) => {}
1168 (None, false) => match (header, last_key_end) {
1169 (Some(_), Some(end)) | (Some(end), None) => {
1170 if !out[end].ends_with('\n') {
1171 out[end].push_str(eol);
1172 }
1173 out.insert(end + 1, new_line("", None));
1174 }
1175 (None, _) => {
1176 if let Some(last) = out.last_mut()
1177 && !last.ends_with('\n')
1178 {
1179 last.push_str(eol);
1180 }
1181 if !out.is_empty() {
1182 out.push(eol.to_owned());
1183 }
1184 out.push(format!("[roles]{eol}"));
1185 out.push(new_line("", None));
1186 }
1187 },
1188 }
1189 Ok(out.concat())
1190}
1191
1192fn patch_count(text: &str, file_key: &str, key: &str, n: usize) -> Result<String, String> {
1201 let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
1202 let spellings = count_spellings(key);
1203 let lines: Vec<&str> = text.split_inclusive('\n').collect();
1204 let mut st = Scan::default();
1205 let mut in_graph = false;
1206 let mut in_table = false;
1207 let mut header: Option<usize> = None;
1208 let mut last_key_end: Option<usize> = None;
1209 let mut found: Vec<(usize, usize)> = Vec::new();
1210 let mut i = 0;
1211 while i < lines.len() {
1212 let trimmed = lines[i].trim();
1213 if !st.open() && trimmed.starts_with('[') {
1214 in_table = true;
1215 in_graph = header.is_none() && is_table_header(trimmed, "graph");
1216 if in_graph {
1217 header = Some(i);
1218 } else if header.is_some() {
1219 break;
1220 }
1221 i += 1;
1222 continue;
1223 }
1224 if !st.open()
1225 && !in_table
1226 && (trimmed.starts_with("graph.") || trimmed.starts_with("graph "))
1227 {
1228 let inline = assigned_key(trimmed).is_some_and(|(k, _)| k == "graph");
1229 if inline || trimmed.starts_with("graph.") {
1230 return Err(
1231 "`graph` is written as an inline or dotted table, which this screen \
1232 cannot edit. Change it by hand."
1233 .to_owned(),
1234 );
1235 }
1236 }
1237 if !st.open()
1238 && let Some((name, _)) = assigned_key(trimmed)
1239 {
1240 let start = i;
1241 let first = lines[i].trim_start();
1242 let at = first.find('=').map_or(0, |p| p + 1);
1243 let mut end = i;
1244 scan_line(&first[at..], &mut st);
1245 while st.open() && end + 1 < lines.len() {
1246 end += 1;
1247 scan_line(lines[end], &mut st);
1248 }
1249 if in_graph {
1250 last_key_end = Some(end);
1251 if spellings.contains(&name.as_str()) {
1252 found.push((start, end));
1253 }
1254 }
1255 i = end + 1;
1256 continue;
1257 }
1258 if st.open() {
1259 scan_line(lines[i], &mut st);
1260 }
1261 i += 1;
1262 }
1263 if found.len() > 1 {
1264 return Err(format!(
1265 "`[graph]` sets `{key}` more than once (it and its alias `candidates`); keep \
1266 only one and try again."
1267 ));
1268 }
1269 let mut out: Vec<String> = lines.iter().map(|l| (*l).to_owned()).collect();
1270 if let Some(&(start, end)) = found.first() {
1271 let body = lines[start..=end].concat();
1272 if start != end || body.contains("{{") || body.contains("{%") {
1273 return Err(format!(
1274 "`{file_key}` is written with a template expression or over several lines, \
1275 which this screen cannot edit without losing it. Change it by hand."
1276 ));
1277 }
1278 let line = lines[start];
1279 let eq = line.find('=').unwrap_or(0) + 1;
1280 let rest = &line[eq..];
1281 let mut scratch = Scan::default();
1282 let code_len = scan_line(rest, &mut scratch).unwrap_or(rest.len());
1283 let value_end = rest[..code_len].trim_end().len();
1284 let lead = rest.len() - rest.trim_start().len();
1285 out[start] = format!(
1286 "{}{}{n}{}",
1287 &line[..eq],
1288 &rest[..lead.min(value_end)],
1289 &rest[value_end..]
1290 );
1291 return Ok(out.concat());
1292 }
1293 let new_line = format!("{key} = {n}{eol}");
1294 match (header, last_key_end) {
1295 (Some(_), Some(end)) | (Some(end), None) => {
1296 if !out[end].ends_with('\n') {
1297 out[end].push_str(eol);
1298 }
1299 out.insert(end + 1, new_line);
1300 }
1301 (None, _) => {
1302 if let Some(last) = out.last_mut()
1303 && !last.ends_with('\n')
1304 {
1305 last.push_str(eol);
1306 }
1307 if !out.is_empty() {
1308 out.push(eol.to_owned());
1309 }
1310 out.push(format!("[graph]{eol}"));
1311 out.push(new_line);
1312 }
1313 }
1314 Ok(out.concat())
1315}
1316
1317#[cfg(test)]
1318mod tests {
1319 use super::*;
1320 use tempfile::TempDir;
1321
1322 fn ids(v: &[&str]) -> Vec<String> {
1323 v.iter().map(|s| (*s).to_owned()).collect()
1324 }
1325
1326 const AGENTS: &str = "[[agents]]\nid = \"a\"\nkind = \"command\"\ncommand = [\"true\"]\n\n\
1327 [[agents]]\nid = \"b\"\nkind = \"command\"\ncommand = [\"true\"]\n";
1328
1329 #[test]
1330 fn patch_keeps_comments_and_unrelated_keys() {
1331 let src = "# top comment\n[vars]\ncache = \"/x\" # keep\n\n[roles]\n# why\nimplementers = [\n \"a\", # first\n \"b\",\n] # tail\njudges = [\"a\"]\nfixer = \"a\"\n\n[graph]\ncandidates = 2\n";
1332 let out = patch_role(src, "implementers", &ids(&["b", "a"])).unwrap();
1333 assert_eq!(
1334 out,
1335 "# top comment\n[vars]\ncache = \"/x\" # keep\n\n[roles]\n# why\nimplementers = [\n \"b\",\n \"a\", # first\n] # tail\njudges = [\"a\"]\nfixer = \"a\"\n\n[graph]\ncandidates = 2\n"
1336 );
1337 let out = patch_role(&out, "judges", &[]).unwrap();
1338 assert!(!out.contains("judges"));
1339 assert!(out.contains("fixer = \"a\"") && out.contains("[graph]"));
1340 }
1341
1342 #[test]
1343 fn patch_does_not_read_a_role_table_out_of_a_multiline_string() {
1344 let src = "[vars]\nexample = \'\'\'\n[roles]\njudges = [\"a\"]\n\'\'\'\nother = \"\"\"\n[roles]\n\"\"\"\n";
1345 assert_eq!(patch_role(src, "judges", &[]).unwrap(), src);
1347 let out = patch_role(src, "judges", &ids(&["a"])).unwrap();
1348 assert!(out.starts_with(src), "{out}");
1349 assert!(out.ends_with("\n[roles]\njudges = [\"a\"]\n"), "{out}");
1350 }
1351
1352 #[test]
1353 fn duplicate_seats_keep_their_own_comments() {
1354 let src =
1355 "[roles]\njudges = [\n \"a\", # first seat\n \"a\", # second seat\n \"b\",\n]\n";
1356 let out = patch_role(src, "judges", &ids(&["b", "a", "a"])).unwrap();
1357 assert_eq!(
1358 out,
1359 "[roles]\njudges = [\n \"b\",\n \"a\", # first seat\n \"a\", # second seat\n]\n"
1360 );
1361 }
1362
1363 #[test]
1364 fn a_reset_keeps_the_comments_of_the_removed_key() {
1365 let out = patch_role(
1366 "[roles]\njudges = [\"a\"] # why a\nfixer = \"a\"\n",
1367 "judges",
1368 &[],
1369 )
1370 .unwrap();
1371 assert_eq!(out, "[roles]\n# why a\nfixer = \"a\"\n");
1372 let out = patch_role(
1373 "[roles]\njudges = [\n # lead\n \"a\", # why a\n]\n",
1374 "judges",
1375 &[],
1376 )
1377 .unwrap();
1378 assert_eq!(out, "[roles]\n# lead\n# why a\n");
1379 }
1380
1381 #[test]
1382 fn a_comment_follows_its_id_through_a_reorder() {
1383 let src =
1384 "[roles]\njudges = [ # head\n # lead\n \"a\", # why a\n \"b\", # why b\n] # tail\n";
1385 let out = patch_role(src, "judges", &ids(&["b", "c", "a"])).unwrap();
1386 assert_eq!(
1387 out,
1388 "[roles]\njudges = [\n # head\n # lead\n \"b\", # why b\n \"c\",\n \"a\", # why a\n] # tail\n"
1389 );
1390 }
1391
1392 #[test]
1393 fn patch_creates_the_table_and_inserts_into_it() {
1394 let out = patch_role("[vars]\nx = 1", "judges", &ids(&["a"])).unwrap();
1395 assert_eq!(out, "[vars]\nx = 1\n\n[roles]\njudges = [\"a\"]\n");
1396 let out = patch_role(
1397 "[roles]\nfixer = \"a\"\n\n[graph]\njudges = 3\n",
1398 "judges",
1399 &ids(&["a"]),
1400 )
1401 .unwrap();
1402 assert_eq!(
1403 out,
1404 "[roles]\nfixer = \"a\"\njudges = [\"a\"]\n\n[graph]\njudges = 3\n"
1405 );
1406 let out = patch_role("[graph]\njudges = 3\n", "judges", &[]).unwrap();
1408 assert_eq!(out, "[graph]\njudges = 3\n");
1409 }
1410
1411 #[test]
1412 fn fixer_is_a_string_for_one_and_an_array_for_a_chain() {
1413 let one = patch_role("", "fixer", &ids(&["a"])).unwrap();
1414 assert!(one.contains("fixer = \"a\""), "{one}");
1415 let two = patch_role("[roles]\nfixer = \"a\"\n", "fixer", &ids(&["a", "b"])).unwrap();
1416 assert!(two.contains("fixer = [\"a\", \"b\"]"), "{two}");
1417 let reset = patch_role(&two, "fixer", &[]).unwrap();
1418 assert!(!reset.contains("fixer ="), "{reset}");
1419 }
1420
1421 #[test]
1422 fn synthesizer_is_a_string_for_one_and_an_array_for_a_chain() {
1423 let one = patch_role("", "synthesizer", &ids(&["a"])).unwrap();
1424 assert!(one.contains("synthesizer = \"a\""), "{one}");
1425 let two = patch_role("", "synthesizer", &ids(&["a", "b"])).unwrap();
1426 assert!(two.contains("synthesizer = [\"a\", \"b\"]"), "{two}");
1427 }
1428
1429 const NEW_CHAIN_KEYS: [&str; 4] = ["chatter", "conductor", "language_judge", "dupes_judge"];
1430
1431 #[test]
1432 fn new_chain_roles_save_round_trip_and_reset() {
1433 for key in NEW_CHAIN_KEYS {
1434 let tmp = TempDir::new().unwrap();
1435 let repo = tmp.path().join("repo");
1436 std::fs::create_dir_all(&repo).unwrap();
1437 std::fs::write(repo.join("magi.toml"), AGENTS).unwrap();
1438 let machine = tmp.path().join("config.toml");
1439 for wanted in [ids(&["b"]), ids(&["b", "a"]), Vec::new()] {
1440 let before = view(&repo, Some(&machine));
1441 let after = save(
1442 &repo,
1443 Some(&machine),
1444 &before.revision,
1445 &BTreeMap::from([(key.to_owned(), wanted.clone())]),
1446 &BTreeMap::new(),
1447 )
1448 .unwrap();
1449 let role = after.roles.iter().find(|r| r.key == key).unwrap();
1450 assert_eq!(role.configured, wanted, "{key}");
1451 assert!(role.chain && role.count.is_none(), "{key}");
1452 let text = std::fs::read_to_string(&machine).unwrap();
1453 if wanted.is_empty() {
1454 assert!(!text.contains(&format!("{key} =")), "{text}");
1455 assert_eq!(role.source, "default");
1456 } else {
1457 assert!(text.contains(&format!("{key} = {}", value_text(key, &wanted))));
1458 assert_eq!(role.source, "machine");
1459 }
1460 let cfg = effective(&layer_paths(&repo, Some(&machine))).unwrap();
1461 assert_eq!(role_ids(&cfg, key), wanted, "{key}");
1462 }
1463 }
1464 }
1465
1466 #[test]
1467 fn new_chain_roles_refuse_repo_overrides_in_words() {
1468 for key in NEW_CHAIN_KEYS {
1469 let tmp = TempDir::new().unwrap();
1470 let repo = tmp.path().join("repo");
1471 std::fs::create_dir_all(&repo).unwrap();
1472 std::fs::write(
1473 repo.join("magi.toml"),
1474 format!("{AGENTS}\n[roles]\n{key} = \"a\"\n"),
1475 )
1476 .unwrap();
1477 let machine = tmp.path().join("config.toml");
1478 let original = "# machine settings\n[vars]\nx = 1\n";
1479 std::fs::write(&machine, original).unwrap();
1480 let before = view(&repo, Some(&machine));
1481 let role = before.roles.iter().find(|r| r.key == key).unwrap();
1482 assert_eq!(role.source, "repo");
1483 assert!(!role.editable);
1484 for wanted in [ids(&["b"]), Vec::new()] {
1485 let err = save(
1486 &repo,
1487 Some(&machine),
1488 &before.revision,
1489 &BTreeMap::from([(key.to_owned(), wanted)]),
1490 &BTreeMap::new(),
1491 )
1492 .unwrap_err();
1493 assert!(
1494 matches!(&err, SaveError::Refused(m)
1495 if m.contains(&format!("This repo overrides roles.{key}"))
1496 && m.contains("edit it there")),
1497 "{err:?}"
1498 );
1499 assert_eq!(std::fs::read_to_string(&machine).unwrap(), original);
1500 }
1501 }
1502 }
1503
1504 #[test]
1505 fn new_chain_roles_show_defaults_inheritance_and_resolution_errors() {
1506 let tmp = TempDir::new().unwrap();
1507 let repo = tmp.path().join("repo");
1508 std::fs::create_dir_all(&repo).unwrap();
1509 let config = repo.join("magi.toml");
1510 std::fs::write(&config, AGENTS).unwrap();
1511 let defaults = view(&repo, None);
1512 for key in ["chatter", "conductor", "dupes_judge"] {
1513 let role = defaults.roles.iter().find(|r| r.key == key).unwrap();
1514 assert_eq!(role.seats, ids(&["a"]), "{key}");
1515 }
1516 let language = defaults
1517 .roles
1518 .iter()
1519 .find(|r| r.key == "language_judge")
1520 .unwrap();
1521 assert!(language.seats.is_empty() && language.seats_error.is_none());
1522 assert_eq!(language.fallback, Some("built-in heuristics"));
1523 std::fs::write(&config, format!("{AGENTS}\n[roles]\nchatter = \"b\"\n")).unwrap();
1524 let inherited = view(&repo, None);
1525 let dupes = inherited
1526 .roles
1527 .iter()
1528 .find(|r| r.key == "dupes_judge")
1529 .unwrap();
1530 assert_eq!(dupes.seats, ids(&["b"]));
1531 assert_eq!(dupes.fallback, Some("chatter"));
1532 std::fs::write(
1534 &config,
1535 format!("{AGENTS}\n[roles]\nchatter = \"b\"\ndupes_judge = []\n"),
1536 )
1537 .unwrap();
1538 let explicit = view(&repo, None);
1539 let dupes = explicit
1540 .roles
1541 .iter()
1542 .find(|r| r.key == "dupes_judge")
1543 .unwrap();
1544 assert_eq!(dupes.seats, ids(&["a"]));
1545 assert_eq!(dupes.fallback, None);
1546 for key in NEW_CHAIN_KEYS {
1547 for (choice, expected) in [
1548 ("[\"missing\", \"b\"]", ids(&["b"])),
1549 ("\"missing\"", Vec::new()),
1550 ] {
1551 std::fs::write(&config, format!("{AGENTS}\n[roles]\n{key} = {choice}\n")).unwrap();
1552 let v = view(&repo, None);
1553 let role = v.roles.iter().find(|r| r.key == key).unwrap();
1554 assert_eq!(role.seats, expected, "{key}");
1555 assert_eq!(role.skipped, ids(&["missing"]), "{key}");
1556 assert_eq!(role.seats_error.is_some(), expected.is_empty(), "{key}");
1557 }
1558 }
1559 }
1560
1561 #[test]
1562 fn patch_refuses_a_templated_value() {
1563 let src = "[roles]\njudges = [\"{{ env.X | default(value='a') }}\"]\n";
1564 assert!(patch_role(src, "judges", &ids(&["a"])).is_err());
1565 }
1566
1567 #[test]
1568 fn save_writes_machine_file_only_and_keeps_comments() {
1569 let tmp = TempDir::new().unwrap();
1570 let repo = tmp.path().join("repo");
1571 std::fs::create_dir_all(&repo).unwrap();
1572 let repo_toml = format!("{AGENTS}\n[graph]\ncandidates = 1\n");
1573 std::fs::write(repo.join("magi.toml"), &repo_toml).unwrap();
1574 let machine = tmp.path().join("cfg").join("magi").join("config.toml");
1575 std::fs::create_dir_all(machine.parent().unwrap()).unwrap();
1576 std::fs::write(
1577 &machine,
1578 "# mine\n[roles]\n# seats\njudges = [\"a\"] # note\n\n[vars]\nx = 1\n",
1579 )
1580 .unwrap();
1581
1582 let v = view(&repo, Some(&machine));
1583 assert!(v.error.is_none(), "{:?}", v.error);
1584 let r = save(
1585 &repo,
1586 Some(&machine),
1587 &v.revision,
1588 &BTreeMap::from([("judges".to_owned(), ids(&["b", "a"]))]),
1589 &BTreeMap::new(),
1590 )
1591 .unwrap();
1592 let text = std::fs::read_to_string(&machine).unwrap();
1593 assert_eq!(
1594 text,
1595 "# mine\n[roles]\n# seats\njudges = [\"b\", \"a\"] # note\n\n[vars]\nx = 1\n"
1596 );
1597 assert_eq!(
1598 std::fs::read_to_string(repo.join("magi.toml")).unwrap(),
1599 repo_toml
1600 );
1601 let judges = r.roles.iter().find(|x| x.key == "judges").unwrap();
1602 assert_eq!(judges.source, "machine");
1603 assert_eq!(judges.configured, ids(&["b", "a"]));
1604 let leftovers = std::fs::read_dir(machine.parent().unwrap())
1606 .unwrap()
1607 .count();
1608 assert_eq!(leftovers, 1);
1609 }
1610
1611 #[test]
1612 fn save_refuses_unknown_ids_and_leaves_the_file_alone() {
1613 let tmp = TempDir::new().unwrap();
1614 let repo = tmp.path().join("repo");
1615 std::fs::create_dir_all(&repo).unwrap();
1616 std::fs::write(repo.join("magi.toml"), AGENTS).unwrap();
1617 let machine = tmp.path().join("m").join("magi").join("config.toml");
1618 let v = view(&repo, Some(&machine));
1619 let err = save(
1620 &repo,
1621 Some(&machine),
1622 &v.revision,
1623 &BTreeMap::from([("judges".to_owned(), ids(&["nope"]))]),
1624 &BTreeMap::new(),
1625 )
1626 .unwrap_err();
1627 assert!(matches!(err, SaveError::Refused(m) if m.contains("nope")));
1628 assert!(!machine.exists());
1629 }
1630
1631 #[test]
1632 fn save_refuses_a_key_the_repo_owns_and_a_stale_revision() {
1633 let tmp = TempDir::new().unwrap();
1634 let repo = tmp.path().join("repo");
1635 std::fs::create_dir_all(&repo).unwrap();
1636 std::fs::write(
1637 repo.join("magi.toml"),
1638 format!("{AGENTS}\n[roles]\njudges = [\"a\"]\n"),
1639 )
1640 .unwrap();
1641 let machine = tmp.path().join("m").join("magi").join("config.toml");
1642 let v = view(&repo, Some(&machine));
1643 let j = v.roles.iter().find(|r| r.key == "judges").unwrap();
1644 assert!(!j.editable && j.source == "repo");
1645 let want = BTreeMap::from([("judges".to_owned(), ids(&["b"]))]);
1646 assert!(matches!(
1647 save(&repo, Some(&machine), &v.revision, &want, &BTreeMap::new()),
1648 Err(SaveError::Refused(_))
1649 ));
1650 let want = BTreeMap::from([("reviewers".to_owned(), ids(&["b"]))]);
1651 assert!(matches!(
1652 save(&repo, Some(&machine), "stale", &want, &BTreeMap::new()),
1653 Err(SaveError::Conflict(_))
1654 ));
1655 }
1656
1657 #[test]
1658 fn a_config_that_does_not_parse_is_an_error_not_an_empty_list() {
1659 let tmp = TempDir::new().unwrap();
1660 let repo = tmp.path().join("repo");
1661 std::fs::create_dir_all(&repo).unwrap();
1662 std::fs::write(repo.join("magi.toml"), "[roles\nbroken").unwrap();
1663 let v = view(&repo, None);
1664 let e = v.error.expect("an error");
1665 assert!(
1666 e.path.is_some_and(|p| p.ends_with("magi.toml")),
1667 "{}",
1668 e.message
1669 );
1670 assert!(v.roles.is_empty() && v.agents.is_empty());
1671 }
1672
1673 #[test]
1674 fn advisors_unset_falls_back_to_judges() {
1675 let tmp = TempDir::new().unwrap();
1676 let repo = tmp.path().join("repo");
1677 std::fs::create_dir_all(&repo).unwrap();
1678 std::fs::write(
1679 repo.join("magi.toml"),
1680 format!("{AGENTS}\n[roles]\njudges = [\"b\"]\n"),
1681 )
1682 .unwrap();
1683 let v = view(&repo, None);
1684 let a = v.roles.iter().find(|r| r.key == "advisors").unwrap();
1685 assert_eq!(a.fallback, Some("judges"));
1686 assert_eq!(a.source, "default");
1687 assert!(
1688 a.seats.iter().all(|s| s == "b") && !a.seats.is_empty(),
1689 "{:?}",
1690 a.seats
1691 );
1692 }
1693
1694 fn two_repos(tmp: &TempDir, other_toml: &str) -> (PathBuf, PathBuf, PathBuf) {
1697 let root = tmp.path().join("ghq");
1698 let repo = root.join("h").join("o").join("cur");
1699 let other = root.join("h").join("o").join("other");
1700 for d in [&repo, &other] {
1701 std::fs::create_dir_all(d.join(".git")).unwrap();
1702 }
1703 std::fs::write(
1704 repo.join("magi.toml"),
1705 format!(
1706 "{AGENTS}\n[repos]\nroots = [{}]\n",
1707 quote(&root.to_string_lossy())
1708 ),
1709 )
1710 .unwrap();
1711 std::fs::write(other.join("magi.toml"), other_toml).unwrap();
1712 let machine = tmp.path().join("m").join("magi").join("config.toml");
1713 (repo, other, machine)
1714 }
1715
1716 #[test]
1717 fn saving_judges_is_refused_when_another_repo_declares_them() {
1718 let tmp = TempDir::new().unwrap();
1719 let (repo, other, machine) =
1720 two_repos(&tmp, &format!("{AGENTS}\n[roles]\njudges = [\"a\"]\n"));
1721 let v = view(&repo, Some(&machine));
1722 let j = v.roles.iter().find(|r| r.key == "judges").unwrap();
1723 assert!(!j.editable, "{:?}", j.locked_reason);
1724 let err = save(
1725 &repo,
1726 Some(&machine),
1727 &v.revision,
1728 &BTreeMap::from([("judges".to_owned(), ids(&["b"]))]),
1729 &BTreeMap::new(),
1730 )
1731 .unwrap_err();
1732 assert!(
1733 matches!(&err, SaveError::Refused(m) if m.contains("o/other")),
1734 "{err:?}"
1735 );
1736 assert!(!machine.exists());
1737 assert!(Config::load_layers(&repo_layers(&other)).is_ok());
1738 save(
1740 &repo,
1741 Some(&machine),
1742 &v.revision,
1743 &BTreeMap::from([("reviewers".to_owned(), ids(&["b"]))]),
1744 &BTreeMap::new(),
1745 )
1746 .unwrap();
1747 let mut layers = vec![machine.clone()];
1748 layers.extend(repo_layers(&other));
1749 assert!(Config::load_layers(&layers).is_ok());
1750 }
1751
1752 #[test]
1753 fn saving_a_role_writes_no_agents_and_detection_stays_dynamic() {
1754 let tmp = TempDir::new().unwrap();
1755 let repo = tmp.path().join("repo");
1756 std::fs::create_dir_all(&repo).unwrap();
1757 std::fs::write(repo.join("magi.toml"), "[graph]\ncandidates = 1\n").unwrap();
1758 let machine = tmp.path().join("m").join("magi").join("config.toml");
1759 let v = view(&repo, Some(&machine));
1760 let Some(first) = Config::autodetected().agents.first().map(|a| a.id.clone()) else {
1761 return; };
1763 save(
1764 &repo,
1765 Some(&machine),
1766 &v.revision,
1767 &BTreeMap::from([("judges".to_owned(), ids(&[&first]))]),
1768 &BTreeMap::new(),
1769 )
1770 .unwrap();
1771 let text = std::fs::read_to_string(&machine).unwrap();
1772 assert!(!text.contains("[[agents]]"), "{text}");
1773 let after = view(&repo, Some(&machine));
1774 assert!(after.agents.iter().all(|a| a.source == "detected"));
1775 assert_eq!(
1776 ids_of(
1777 &Config::load_layers(&layer_paths(&repo, Some(&machine)))
1778 .unwrap()
1779 .agents
1780 ),
1781 ids_of(&Config::autodetected().agents)
1782 );
1783 }
1784
1785 #[test]
1786 fn an_explicit_empty_agents_list_is_kept() {
1787 let tmp = TempDir::new().unwrap();
1788 let f = tmp.path().join("magi.toml");
1789 std::fs::write(&f, "agents = []\n").unwrap();
1790 assert!(Config::load_layers(&[f]).unwrap().agents.is_empty());
1791 }
1792
1793 #[test]
1794 fn the_repo_lock_says_the_repo_overrides_the_key() {
1795 let tmp = TempDir::new().unwrap();
1796 let repo = tmp.path().join("repo");
1797 std::fs::create_dir_all(&repo).unwrap();
1798 std::fs::write(
1799 repo.join("magi.toml"),
1800 format!("{AGENTS}\n[roles]\njudges = [\"a\"]\n"),
1801 )
1802 .unwrap();
1803 let machine = tmp.path().join("m").join("magi").join("config.toml");
1804 let v = view(&repo, Some(&machine));
1805 let j = v.roles.iter().find(|r| r.key == "judges").unwrap();
1806 let why = j.locked_reason.as_deref().unwrap();
1807 assert!(
1808 why.starts_with("This repo overrides roles.judges in "),
1809 "{why}"
1810 );
1811 }
1812
1813 #[test]
1814 fn patch_count_replaces_in_place_and_keeps_the_rest() {
1815 let src =
1816 "# top\n[graph]\n# seats\njudges = 3 # three\nreviewers = 2\n\n[vars]\nx = 1\n";
1817 let out = patch_count(src, "judges", "judges", 5).unwrap();
1818 assert_eq!(
1819 out,
1820 "# top\n[graph]\n# seats\njudges = 5 # three\nreviewers = 2\n\n[vars]\nx = 1\n"
1821 );
1822 }
1823
1824 #[test]
1825 fn patch_count_keeps_the_alias_spelling() {
1826 let src = "[graph]\ncandidates = 2\n";
1827 let out = patch_count(src, "candidates", "implementers", 4).unwrap();
1828 assert_eq!(out, "[graph]\ncandidates = 4\n");
1829 assert!(!out.contains("implementers"));
1830 }
1831
1832 #[test]
1833 fn patch_count_refuses_both_spellings() {
1834 let src = "[graph]\ncandidates = 2\nimplementers = 3\n";
1835 assert!(patch_count(src, "implementers", "implementers", 4).is_err());
1836 }
1837
1838 #[test]
1839 fn patch_count_adds_the_key_after_the_last_graph_key() {
1840 let src = "[graph]\nreviewers = 2 # r\n\n[roles]\njudges = [\"a\"]\n";
1841 let out = patch_count(src, "judges", "judges", 2).unwrap();
1842 assert_eq!(
1843 out,
1844 "[graph]\nreviewers = 2 # r\njudges = 2\n\n[roles]\njudges = [\"a\"]\n"
1845 );
1846 let empty = patch_count("[graph]\n", "advisors", "advisors", 0).unwrap();
1847 assert_eq!(empty, "[graph]\nadvisors = 0\n");
1848 }
1849
1850 #[test]
1851 fn patch_count_creates_a_missing_graph_table_and_keeps_crlf() {
1852 let out = patch_count("# c\n[roles]\njudges = [\"a\"]", "judges", "judges", 2).unwrap();
1853 assert_eq!(
1854 out,
1855 "# c\n[roles]\njudges = [\"a\"]\n\n[graph]\njudges = 2\n"
1856 );
1857 assert_eq!(
1858 patch_count("", "judges", "judges", 2).unwrap(),
1859 "[graph]\njudges = 2\n"
1860 );
1861 let crlf = patch_count("[graph]\r\nreviewers = 2\r\n", "judges", "judges", 2).unwrap();
1862 assert_eq!(crlf, "[graph]\r\nreviewers = 2\r\njudges = 2\r\n");
1863 }
1864
1865 #[test]
1866 fn patch_count_refuses_what_it_cannot_rewrite_in_place() {
1867 assert!(patch_count("[graph]\njudges = {{ vars.n }}\n", "judges", "judges", 2).is_err());
1868 assert!(patch_count("graph = { judges = 2 }\n", "judges", "judges", 3).is_err());
1869 assert!(patch_count("graph.judges = 2\n", "judges", "judges", 3).is_err());
1870 assert!(patch_count("[graph]\njudges = \\\n", "judges", "judges", 3).is_ok());
1871 }
1872
1873 #[test]
1874 fn save_writes_a_count_through_the_alias_and_refuses_bad_ones() {
1875 let tmp = TempDir::new().unwrap();
1876 let repo = tmp.path().join("repo");
1877 std::fs::create_dir_all(&repo).unwrap();
1878 std::fs::write(
1879 repo.join("magi.toml"),
1880 "[[agents]]\nid = \"a\"\nkind = \"command\"\ncommand = [\"true\"]\n",
1881 )
1882 .unwrap();
1883 let machine = tmp.path().join("m").join("magi").join("config.toml");
1884 std::fs::create_dir_all(machine.parent().unwrap()).unwrap();
1885 std::fs::write(&machine, "[graph]\ncandidates = 1 # old\n").unwrap();
1886 let v = view(&repo, Some(&machine));
1887 let c = |n: serde_json::Value| BTreeMap::from([("implementers".to_owned(), n)]);
1888 for bad in [
1889 serde_json::json!(0),
1890 serde_json::json!(2.5),
1891 serde_json::json!("x"),
1892 serde_json::json!(-1),
1893 ] {
1894 let err = save(
1895 &repo,
1896 Some(&machine),
1897 &v.revision,
1898 &BTreeMap::new(),
1899 &c(bad),
1900 )
1901 .unwrap_err();
1902 assert!(matches!(err, SaveError::Refused(_)), "{err:?}");
1903 }
1904 save(
1905 &repo,
1906 Some(&machine),
1907 &v.revision,
1908 &BTreeMap::new(),
1909 &c(serde_json::json!(2)),
1910 )
1911 .unwrap();
1912 assert_eq!(
1913 std::fs::read_to_string(&machine).unwrap(),
1914 "[graph]\ncandidates = 2 # old\n"
1915 );
1916 let after = view(&repo, Some(&machine));
1917 let count = after.roles[0].count.as_ref().unwrap();
1918 assert_eq!(
1919 (count.value, count.file_key, count.backups),
1920 (2, "candidates", Some(0))
1921 );
1922 save(
1924 &repo,
1925 Some(&machine),
1926 &after.revision,
1927 &BTreeMap::new(),
1928 &BTreeMap::from([("advisors".to_owned(), serde_json::json!(0))]),
1929 )
1930 .unwrap();
1931 }
1932}