1use std::collections::BTreeMap;
5use std::path::{Path, PathBuf};
6use std::time::Duration;
7
8use serde::{Deserialize, Serialize};
9
10use crate::plan::is_valid_id;
11use crate::store::write_text_atomically;
12
13#[derive(Debug, Clone, PartialEq)]
14pub struct Config {
15 pub run: RunSettings,
16 pub policy: PolicySettings,
17 pub roles: Roles,
18 pub lanes: BTreeMap<String, Lane>,
19}
20
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct RunSettings {
23 pub max_attempts: u32,
24 pub idle_timeout: Duration,
25 pub job_timeout: Duration,
26}
27
28#[derive(Debug, Clone, PartialEq)]
29pub struct PolicySettings {
30 pub min_remaining: f64,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct Roles {
36 pub planner: Vec<String>,
37 pub reviewer: Vec<String>,
38 pub worker: Vec<String>,
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum HarnessKind {
43 Claude,
44 Agy,
45 Codex,
46 OpenCode,
47 Fake,
49}
50
51impl HarnessKind {
52 pub fn name(self) -> &'static str {
54 match self {
55 HarnessKind::Claude => "claude",
56 HarnessKind::Agy => "agy",
57 HarnessKind::Codex => "codex",
58 HarnessKind::OpenCode => "opencode",
59 HarnessKind::Fake => "fake",
60 }
61 }
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
66#[serde(rename_all = "snake_case")]
67pub enum Mode {
68 Off,
69 Handover,
71 Direct,
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
75#[serde(rename_all = "snake_case")]
76pub enum CodexProvider {
77 Deepseek,
78 Openai,
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
82#[serde(rename_all = "snake_case")]
83pub enum Effort {
84 Low,
85 Medium,
86 High,
87 Xhigh,
88 Max,
89}
90
91impl Effort {
92 pub fn as_str(self) -> &'static str {
93 const NAMES: [&str; 5] = ["low", "medium", "high", "xhigh", "max"];
94 NAMES[self as usize]
95 }
96}
97
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct Lane {
100 pub harness: HarnessKind,
101 pub bin: String,
103 pub provider: Option<CodexProvider>,
105 pub model: Option<String>,
107 pub effort: Effort,
108 pub ultracode: bool,
109 pub mode: Mode,
110 pub quota_group: Option<String>,
111 pub accept_vendor_terms_risk: bool,
112 pub script: Option<PathBuf>,
114}
115
116impl Lane {
117 pub fn is_manual(&self) -> bool {
119 self.mode == Mode::Handover
120 }
121
122 pub fn is_off(&self) -> bool {
123 self.mode == Mode::Off
124 }
125}
126
127pub const EXAMPLE: &str = r#"[run]
129max_attempts = 5
130idle_timeout = "5m"
131job_timeout = "30m"
132
133[policy]
134min_remaining = 0.05
135
136[roles]
137planner = ["plan"]
138worker = ["gemini", "deepseek"]
139reviewer = ["review"]
140
141[lanes.plan]
142harness = "claude"
143model = "opus"
144effort = "medium"
145
146[lanes.review]
147harness = "claude"
148model = "sonnet"
149effort = "low"
150
151[lanes.deepseek]
152harness = "codex"
153model = "deepseek-flash"
154
155[lanes.gemini]
156harness = "agy"
157mode = "handover"
158model = "gemini-4-hydrogen-medium"
159quota_group = "Gemini Models"
160# accept_vendor_terms_risk = true # required for mode = "direct"
161"#;
162
163#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
164pub enum ConfigError {
165 #[error("no configuration file at {}; create one (an example follows)", .0.display())]
166 Missing(PathBuf),
167 #[error("cannot read {}: {message}", path.display())]
168 Unreadable { path: PathBuf, message: String },
169 #[error("cannot write {}: {message}", path.display())]
170 Unwritable { path: PathBuf, message: String },
171 #[error("the configuration is not valid TOML of the expected shape: {0}")]
172 Syntax(String),
173 #[error("{key}: {problem}")]
174 Invalid { key: String, problem: String },
175}
176
177fn invalid(key: impl Into<String>, problem: impl Into<String>) -> ConfigError {
178 ConfigError::Invalid {
179 key: key.into(),
180 problem: problem.into(),
181 }
182}
183
184pub fn default_path(xdg_config_home: Option<&str>, home: Option<&str>) -> Option<PathBuf> {
187 let base = match (xdg_config_home.filter(|v| !v.is_empty()), home) {
188 (Some(xdg), _) => PathBuf::from(xdg),
189 (None, Some(home)) if !home.is_empty() => Path::new(home).join(".config"),
190 _ => return None,
191 };
192 Some(base.join("onerig").join("config.toml"))
193}
194
195pub fn load(path: &Path, allow_fake: bool) -> Result<Config, ConfigError> {
196 let text = std::fs::read_to_string(path).map_err(|e| match e.kind() {
197 std::io::ErrorKind::NotFound => ConfigError::Missing(path.to_path_buf()),
198 _ => ConfigError::Unreadable {
199 path: path.to_path_buf(),
200 message: e.to_string(),
201 },
202 })?;
203 parse(&text, allow_fake)
204}
205
206pub fn parse_duration(text: &str) -> Option<Duration> {
208 let seconds_per_unit = match text.chars().last()? {
209 's' => 1,
210 'm' => 60,
211 'h' => 3600,
212 _ => return None,
213 };
214 let number = &text[..text.len() - 1];
216 if !number.bytes().all(|b| b.is_ascii_digit()) {
217 return None;
218 }
219 let value: u64 = number.parse().ok()?;
220 value.checked_mul(seconds_per_unit).map(Duration::from_secs)
221}
222
223pub fn parse(text: &str, allow_fake: bool) -> Result<Config, ConfigError> {
224 let raw: RawConfig = toml::from_str(text).map_err(|e| ConfigError::Syntax(e.to_string()))?;
225 let run = run_settings(&raw.run)?;
226 let policy = policy_settings(&raw.policy)?;
227 let lanes = raw
228 .lanes
229 .iter()
230 .map(|(name, lane)| Ok((name.clone(), lane_from(name, lane, allow_fake)?)))
231 .collect::<Result<BTreeMap<_, _>, ConfigError>>()?;
232 let roles = roles_from(&raw.roles, &lanes)?;
233 Ok(Config {
234 run,
235 policy,
236 roles,
237 lanes,
238 })
239}
240
241#[derive(Deserialize)]
242#[serde(deny_unknown_fields)]
243struct RawConfig {
244 #[serde(default)]
245 run: RawRun,
246 #[serde(default)]
247 policy: RawPolicy,
248 roles: RawRoles,
249 lanes: BTreeMap<String, RawLane>,
250}
251
252#[derive(Deserialize, Default)]
253#[serde(deny_unknown_fields)]
254struct RawRun {
255 max_attempts: Option<i64>,
256 idle_timeout: Option<String>,
257 job_timeout: Option<String>,
258}
259
260#[derive(Deserialize, Default)]
261#[serde(deny_unknown_fields)]
262struct RawPolicy {
263 min_remaining: Option<f64>,
264}
265
266#[derive(Deserialize)]
267#[serde(deny_unknown_fields)]
268struct RawRoles {
269 planner: Vec<String>,
270 reviewer: Vec<String>,
271 worker: Vec<String>,
272}
273
274#[derive(Deserialize)]
275#[serde(deny_unknown_fields)]
276struct RawLane {
277 harness: String,
278 bin: Option<String>,
279 provider: Option<String>,
280 model: Option<String>,
281 effort: Option<String>,
282 ultracode: Option<bool>,
283 mode: Option<String>,
284 quota_group: Option<String>,
285 accept_vendor_terms_risk: Option<bool>,
286 script: Option<PathBuf>,
287}
288
289fn run_settings(raw: &RawRun) -> Result<RunSettings, ConfigError> {
290 let max_attempts = raw.max_attempts.unwrap_or(5);
291 if !(1..=20).contains(&max_attempts) {
292 return Err(invalid("run.max_attempts", "use a number from 1 to 20"));
293 }
294 Ok(RunSettings {
295 max_attempts: max_attempts as u32,
296 idle_timeout: duration_setting("run.idle_timeout", raw.idle_timeout.as_deref(), 300)?,
297 job_timeout: duration_setting("run.job_timeout", raw.job_timeout.as_deref(), 1800)?,
298 })
299}
300
301fn duration_setting(
302 key: &str,
303 text: Option<&str>,
304 default_secs: u64,
305) -> Result<Duration, ConfigError> {
306 let Some(text) = text else {
307 return Ok(Duration::from_secs(default_secs));
308 };
309 match parse_duration(text) {
310 Some(duration) if duration >= Duration::from_secs(1) => Ok(duration),
311 Some(_) => Err(invalid(key, "use at least 1s")),
312 None => Err(invalid(
313 key,
314 "use a whole number followed by s, m or h, for example \"5m\"",
315 )),
316 }
317}
318
319fn policy_settings(raw: &RawPolicy) -> Result<PolicySettings, ConfigError> {
320 let min_remaining = raw.min_remaining.unwrap_or(0.05);
321 if !(0.0..=1.0).contains(&min_remaining) {
322 return Err(invalid("policy.min_remaining", "use a number from 0 to 1"));
323 }
324 Ok(PolicySettings { min_remaining })
325}
326
327fn lane_from(name: &str, raw: &RawLane, allow_fake: bool) -> Result<Lane, ConfigError> {
328 if !is_valid_id(name) {
329 return Err(invalid(
330 format!("lanes.{name}"),
331 "a lane name uses lowercase letters, digits, '-' and '_', at most 32 characters",
332 ));
333 }
334 let harness = harness_kind(name, &raw.harness, allow_fake)?;
335 check_keys_apply(name, raw, harness)?;
336 let mode = mode_of(name, raw, harness)?;
337 check_direct_agy(name, raw, harness, mode)?;
338 build_lane(name, raw, harness, mode)
339}
340
341fn build_lane(
342 name: &str,
343 raw: &RawLane,
344 harness: HarnessKind,
345 mode: Mode,
346) -> Result<Lane, ConfigError> {
347 Ok(Lane {
348 harness,
349 bin: raw
350 .bin
351 .clone()
352 .unwrap_or_else(|| harness.name().to_string()),
353 provider: provider_of(name, raw, harness)?,
354 model: required(
355 name,
356 "model",
357 raw.model.clone(),
358 harness != HarnessKind::Fake,
359 )?,
360 effort: effort_of(name, raw)?,
361 ultracode: raw.ultracode.unwrap_or(false),
362 mode,
363 quota_group: raw.quota_group.clone(),
364 accept_vendor_terms_risk: raw.accept_vendor_terms_risk.unwrap_or(false),
365 script: required(
366 name,
367 "script",
368 raw.script.clone(),
369 harness == HarnessKind::Fake,
370 )?,
371 })
372}
373
374fn harness_kind(name: &str, text: &str, allow_fake: bool) -> Result<HarnessKind, ConfigError> {
375 let key = format!("lanes.{name}.harness");
376 match text {
377 "claude" => Ok(HarnessKind::Claude),
378 "agy" => Ok(HarnessKind::Agy),
379 "codex" => Ok(HarnessKind::Codex),
380 "opencode" => Ok(HarnessKind::OpenCode),
381 "fake" if allow_fake => Ok(HarnessKind::Fake),
382 "fake" => Err(invalid(
383 key,
384 "fake lanes are for tests and need ONERIG_TEST to be set",
385 )),
386 _ => Err(invalid(key, "use claude, agy, codex or opencode")),
387 }
388}
389
390fn check_keys_apply(name: &str, raw: &RawLane, harness: HarnessKind) -> Result<(), ConfigError> {
391 use HarnessKind::{Agy, Claude, Codex, Fake, OpenCode};
392 let rules: [(&str, bool, &[HarnessKind]); 8] = [
393 ("provider", raw.provider.is_some(), &[Codex]),
394 (
395 "model",
396 raw.model.is_some(),
397 &[Claude, Agy, Codex, OpenCode],
398 ),
399 ("effort", raw.effort.is_some(), &[Claude]),
400 ("ultracode", raw.ultracode.is_some(), &[Claude]),
401 ("mode", raw.mode.is_some(), &[Agy]),
402 ("quota_group", raw.quota_group.is_some(), &[Agy]),
403 (
404 "accept_vendor_terms_risk",
405 raw.accept_vendor_terms_risk.is_some(),
406 &[Agy],
407 ),
408 ("script", raw.script.is_some(), &[Fake]),
409 ];
410 match rules
411 .iter()
412 .find(|(_, set, allowed)| *set && !allowed.contains(&harness))
413 {
414 Some((key, _, _)) => Err(invalid(
415 format!("lanes.{name}.{key}"),
416 format!("does not apply to a {} lane", harness.name()),
417 )),
418 None => Ok(()),
419 }
420}
421
422fn provider_of(
423 name: &str,
424 raw: &RawLane,
425 harness: HarnessKind,
426) -> Result<Option<CodexProvider>, ConfigError> {
427 if harness != HarnessKind::Codex {
428 return Ok(None);
429 }
430 match raw.provider.as_deref().unwrap_or("deepseek") {
431 "deepseek" => Ok(Some(CodexProvider::Deepseek)),
432 "openai" => Ok(Some(CodexProvider::Openai)),
433 _ => Err(invalid(
434 format!("lanes.{name}.provider"),
435 "use deepseek or openai",
436 )),
437 }
438}
439
440fn required<T>(
441 name: &str,
442 key: &str,
443 value: Option<T>,
444 needed: bool,
445) -> Result<Option<T>, ConfigError> {
446 match (needed, value) {
447 (true, None) => Err(invalid(format!("lanes.{name}.{key}"), "is required")),
448 (_, value) => Ok(value),
449 }
450}
451
452fn mode_of(name: &str, raw: &RawLane, harness: HarnessKind) -> Result<Mode, ConfigError> {
453 if harness != HarnessKind::Agy {
454 return Ok(Mode::Direct);
455 }
456 match raw.mode.as_deref().unwrap_or("handover") {
457 "off" => Ok(Mode::Off),
458 "handover" => Ok(Mode::Handover),
459 "direct" => Ok(Mode::Direct),
460 _ => Err(invalid(
461 format!("lanes.{name}.mode"),
462 "use off, handover or direct",
463 )),
464 }
465}
466
467fn check_direct_agy(
468 name: &str,
469 raw: &RawLane,
470 harness: HarnessKind,
471 mode: Mode,
472) -> Result<(), ConfigError> {
473 if harness != HarnessKind::Agy || mode != Mode::Direct {
474 return Ok(());
475 }
476 if raw.accept_vendor_terms_risk != Some(true) {
477 return Err(invalid(
478 format!("lanes.{name}.accept_vendor_terms_risk"),
479 "mode = \"direct\" lets onerig drive agy on your Google sign-in, which Google's \
480 Antigravity terms treat as a breach that can suspend the account; set this to true \
481 to accept that risk",
482 ));
483 }
484 required(name, "quota_group", raw.quota_group.as_ref(), true).map(|_| ())
485}
486
487fn effort_of(name: &str, raw: &RawLane) -> Result<Effort, ConfigError> {
488 match raw.effort.as_deref().unwrap_or("medium") {
489 "low" => Ok(Effort::Low),
490 "medium" => Ok(Effort::Medium),
491 "high" => Ok(Effort::High),
492 "xhigh" => Ok(Effort::Xhigh),
493 "max" => Ok(Effort::Max),
494 _ => Err(invalid(
495 format!("lanes.{name}.effort"),
496 "use low, medium, high, xhigh or max",
497 )),
498 }
499}
500
501fn roles_from(raw: &RawRoles, lanes: &BTreeMap<String, Lane>) -> Result<Roles, ConfigError> {
502 Ok(Roles {
503 planner: auto_role_lanes("roles.planner", &raw.planner, lanes)?,
504 reviewer: auto_role_lanes("roles.reviewer", &raw.reviewer, lanes)?,
505 worker: worker_lanes(&raw.worker, lanes)?,
506 })
507}
508
509fn existing<'a>(
510 key: &str,
511 name: &str,
512 lanes: &'a BTreeMap<String, Lane>,
513) -> Result<&'a Lane, ConfigError> {
514 lanes
515 .get(name)
516 .ok_or_else(|| invalid(key, format!("there is no lane named {name}")))
517}
518
519fn distinct_lanes(
520 key: &str,
521 names: &[String],
522 lanes: &BTreeMap<String, Lane>,
523) -> Result<(), ConfigError> {
524 if names.is_empty() {
525 return Err(invalid(key, "name at least one lane"));
526 }
527 for (index, name) in names.iter().enumerate() {
528 if names[..index].contains(name) {
529 return Err(invalid(key, format!("lane {name} is named twice")));
530 }
531 let _ = existing(key, name, lanes)?;
532 }
533 Ok(())
534}
535
536fn auto_role_lanes(
537 key: &str,
538 names: &[String],
539 lanes: &BTreeMap<String, Lane>,
540) -> Result<Vec<String>, ConfigError> {
541 distinct_lanes(key, names, lanes)?;
542 for name in names {
543 let lane = &lanes[name];
544 if lane.is_off() || lane.is_manual() {
545 return Err(invalid(
546 key,
547 format!(
548 "lane {name} is manual or off; planner and reviewer lanes must run automatically"
549 ),
550 ));
551 }
552 }
553 Ok(names.to_vec())
554}
555
556fn worker_lanes(
557 names: &[String],
558 lanes: &BTreeMap<String, Lane>,
559) -> Result<Vec<String>, ConfigError> {
560 const KEY: &str = "roles.worker";
561 distinct_lanes(KEY, names, lanes)?;
562 if names.iter().all(|name| lanes[name].is_off()) {
563 return Err(invalid(KEY, "at least one worker lane must not be off"));
564 }
565 Ok(names.to_vec())
566}
567
568pub fn to_toml(config: &Config) -> String {
570 let out = OutConfig {
571 run: OutRun {
572 max_attempts: config.run.max_attempts,
573 idle_timeout: format_duration(config.run.idle_timeout),
574 job_timeout: format_duration(config.run.job_timeout),
575 },
576 policy: OutPolicy {
577 min_remaining: config.policy.min_remaining,
578 },
579 roles: OutRoles {
580 planner: &config.roles.planner,
581 reviewer: &config.roles.reviewer,
582 worker: &config.roles.worker,
583 },
584 lanes: config
585 .lanes
586 .iter()
587 .map(|(name, lane)| (name.clone(), out_lane(lane)))
588 .collect(),
589 };
590 toml::to_string_pretty(&out).unwrap_or_default()
591}
592
593pub fn save(path: &Path, config: &Config) -> Result<(), ConfigError> {
595 let err = |e: std::io::Error| ConfigError::Unwritable {
596 path: path.to_path_buf(),
597 message: e.to_string(),
598 };
599 if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
600 std::fs::create_dir_all(parent).map_err(err)?;
601 }
602 write_text_atomically(path, &to_toml(config)).map_err(err)
603}
604
605#[derive(Serialize)]
606struct OutConfig<'a> {
607 run: OutRun,
608 policy: OutPolicy,
609 roles: OutRoles<'a>,
610 lanes: BTreeMap<String, OutLane<'a>>,
611}
612
613#[derive(Serialize)]
614struct OutRun {
615 max_attempts: u32,
616 idle_timeout: String,
617 job_timeout: String,
618}
619
620#[derive(Serialize)]
621struct OutPolicy {
622 min_remaining: f64,
623}
624
625#[derive(Serialize)]
626struct OutRoles<'a> {
627 planner: &'a [String],
628 reviewer: &'a [String],
629 worker: &'a [String],
630}
631
632#[derive(Serialize)]
633struct OutLane<'a> {
634 harness: &'static str,
635 #[serde(skip_serializing_if = "Option::is_none")]
636 bin: Option<&'a str>,
637 #[serde(skip_serializing_if = "Option::is_none")]
638 provider: Option<CodexProvider>,
639 #[serde(skip_serializing_if = "Option::is_none")]
640 model: Option<&'a str>,
641 #[serde(skip_serializing_if = "Option::is_none")]
642 effort: Option<Effort>,
643 #[serde(skip_serializing_if = "Option::is_none")]
644 ultracode: Option<bool>,
645 #[serde(skip_serializing_if = "Option::is_none")]
646 mode: Option<Mode>,
647 #[serde(skip_serializing_if = "Option::is_none")]
648 quota_group: Option<&'a str>,
649 #[serde(skip_serializing_if = "Option::is_none")]
650 accept_vendor_terms_risk: Option<bool>,
651 #[serde(skip_serializing_if = "Option::is_none")]
652 script: Option<String>,
653}
654
655fn out_lane(lane: &Lane) -> OutLane<'_> {
656 let custom_bin = (lane.bin != lane.harness.name()).then_some(lane.bin.as_str());
657 let is = |kind| lane.harness == kind;
658 OutLane {
659 harness: lane.harness.name(),
660 bin: custom_bin,
661 provider: lane.provider.filter(|_| is(HarnessKind::Codex)),
662 model: (!is(HarnessKind::Fake))
663 .then_some(lane.model.as_deref())
664 .flatten(),
665 effort: is(HarnessKind::Claude).then_some(lane.effort),
666 ultracode: (is(HarnessKind::Claude) && lane.ultracode).then_some(true),
667 mode: is(HarnessKind::Agy).then_some(lane.mode),
668 quota_group: is(HarnessKind::Agy)
669 .then_some(lane.quota_group.as_deref())
670 .flatten(),
671 accept_vendor_terms_risk: (is(HarnessKind::Agy) && lane.accept_vendor_terms_risk)
672 .then_some(true),
673 script: is(HarnessKind::Fake)
674 .then(|| lane.script.as_ref().map(|p| p.display().to_string()))
675 .flatten(),
676 }
677}
678
679fn format_duration(duration: Duration) -> String {
680 let secs = duration.as_secs();
681 if secs >= 3600 && secs.is_multiple_of(3600) {
682 format!("{}h", secs / 3600)
683 } else if secs >= 60 && secs.is_multiple_of(60) {
684 format!("{}m", secs / 60)
685 } else {
686 format!("{secs}s")
687 }
688}
689
690#[cfg(test)]
691mod tests {
692 use super::*;
693
694 const BASE: &str = r#"
695[roles]
696planner = ["plan"]
697reviewer = ["review"]
698worker = ["deepseek"]
699
700[lanes.plan]
701harness = "claude"
702model = "sonnet"
703
704[lanes.review]
705harness = "claude"
706model = "sonnet"
707
708[lanes.deepseek]
709harness = "codex"
710model = "deepseek-flash"
711"#;
712
713 const GEMINI: &str = "\n[lanes.gemini]\nharness = \"agy\"\nmodel = \"m\"\n";
714
715 fn with(extra: &str) -> String {
717 format!("{BASE}{extra}\n")
718 }
719
720 fn with_gemini(extra: &str) -> String {
721 with(&format!("{GEMINI}{extra}")).replace(
722 r#"worker = ["deepseek"]"#,
723 r#"worker = ["deepseek", "gemini"]"#,
724 )
725 }
726
727 fn invalid_key(text: &str) -> String {
728 match parse(text, false) {
729 Err(ConfigError::Invalid { key, .. }) => key,
730 other => panic!("expected an invalid key, got {other:?}"),
731 }
732 }
733
734 #[test]
735 fn the_example_is_valid_and_keeps_agy_manual() {
736 let config = parse(EXAMPLE, false).unwrap();
737
738 assert_eq!(config.roles.worker, ["gemini", "deepseek"]);
739 assert_eq!(config.lanes["plan"].model.as_deref(), Some("opus"));
740 assert_eq!(config.lanes["gemini"].mode, Mode::Handover);
741 assert!(config.lanes["gemini"].is_manual());
742 assert_eq!(config.lanes["deepseek"].mode, Mode::Direct);
743 assert_eq!(
744 config.lanes["deepseek"].provider,
745 Some(CodexProvider::Deepseek)
746 );
747 assert_eq!(config.lanes["review"].effort, Effort::Low);
748 }
749
750 #[test]
751 fn missing_settings_take_their_defaults() {
752 let config = parse(BASE, false).unwrap();
753
754 assert_eq!(config.run.max_attempts, 5);
755 assert_eq!(config.run.idle_timeout, Duration::from_secs(300));
756 assert_eq!(config.run.job_timeout, Duration::from_secs(1800));
757 assert_eq!(config.policy.min_remaining, 0.05);
758 assert_eq!(config.lanes["deepseek"].bin, "codex");
759 assert_eq!(config.lanes["plan"].effort, Effort::Medium);
760 assert_eq!(config.roles.planner, ["plan"]);
761 }
762
763 #[test]
764 fn an_unknown_key_or_a_wrong_type_is_a_syntax_error_naming_it() {
765 let unknown = parse(&with("\n[run]\nmax_attempt = 3"), false);
766 let wrong_type = parse(&with("\n[run]\nmax_attempts = \"3\""), false);
767
768 assert!(matches!(&unknown, Err(ConfigError::Syntax(m)) if m.contains("max_attempt")));
769 assert!(matches!(wrong_type, Err(ConfigError::Syntax(_))));
770 }
771
772 #[test]
773 fn max_attempts_must_be_from_1_to_20() {
774 assert_eq!(
775 invalid_key(&with("\n[run]\nmax_attempts = 0")),
776 "run.max_attempts"
777 );
778 assert_eq!(
779 invalid_key(&with("\n[run]\nmax_attempts = 21")),
780 "run.max_attempts"
781 );
782 assert_eq!(
783 parse(&with("\n[run]\nmax_attempts = 20"), false)
784 .unwrap()
785 .run
786 .max_attempts,
787 20
788 );
789 }
790
791 #[test]
792 fn durations_need_a_unit_and_at_least_one_second() {
793 for bad in ["\"5\"", "\"5d\"", "\"m\"", "\"0s\"", "\"-1s\""] {
794 assert_eq!(
795 invalid_key(&with(&format!("\n[run]\nidle_timeout = {bad}"))),
796 "run.idle_timeout",
797 "{bad}"
798 );
799 }
800 let config = parse(
801 &with("\n[run]\nidle_timeout = \"1s\"\njob_timeout = \"2h\""),
802 false,
803 )
804 .unwrap();
805 assert_eq!(config.run.idle_timeout, Duration::from_secs(1));
806 assert_eq!(config.run.job_timeout, Duration::from_secs(7200));
807 }
808
809 #[test]
810 fn parse_duration_reads_seconds_minutes_and_hours_only() {
811 assert_eq!(parse_duration("45s"), Some(Duration::from_secs(45)));
812 assert_eq!(parse_duration("5m"), Some(Duration::from_secs(300)));
813 assert_eq!(parse_duration("1h"), Some(Duration::from_secs(3600)));
814 for bad in ["", "s", "5", "5x", " 5m", "5.5m", "+5m", "é"] {
815 assert_eq!(parse_duration(bad), None, "{bad:?}");
816 }
817 }
818
819 #[test]
820 fn min_remaining_must_be_from_0_to_1() {
821 assert_eq!(
822 invalid_key(&with("\n[policy]\nmin_remaining = 1.5")),
823 "policy.min_remaining"
824 );
825 assert_eq!(
826 invalid_key(&with("\n[policy]\nmin_remaining = -0.1")),
827 "policy.min_remaining"
828 );
829 assert_eq!(
830 parse(&with("\n[policy]\nmin_remaining = 1.0"), false)
831 .unwrap()
832 .policy
833 .min_remaining,
834 1.0
835 );
836 }
837
838 #[test]
839 fn a_lane_name_must_be_safe() {
840 let text = with("\n[lanes.Deep]\nharness = \"codex\"\nmodel = \"m\"");
841
842 assert_eq!(invalid_key(&text), "lanes.Deep");
843 }
844
845 #[test]
846 fn an_unknown_harness_is_rejected() {
847 let text = BASE.replace(r#"harness = "codex""#, r#"harness = "aider""#);
848
849 assert_eq!(invalid_key(&text), "lanes.deepseek.harness");
850 }
851
852 #[test]
853 fn a_key_on_a_lane_whose_harness_it_does_not_apply_to_is_rejected() {
854 assert_eq!(
855 invalid_key(&with("effort = \"low\"")),
856 "lanes.deepseek.effort"
857 );
858 assert_eq!(
859 invalid_key(&with("ultracode = true")),
860 "lanes.deepseek.ultracode"
861 );
862 assert_eq!(invalid_key(&with("mode = \"off\"")), "lanes.deepseek.mode");
863 assert_eq!(
864 invalid_key(&with("quota_group = \"g\"")),
865 "lanes.deepseek.quota_group"
866 );
867 assert_eq!(
868 invalid_key(&with("accept_vendor_terms_risk = true")),
869 "lanes.deepseek.accept_vendor_terms_risk"
870 );
871 assert_eq!(
872 invalid_key(&with("script = \"s.json\"")),
873 "lanes.deepseek.script"
874 );
875 assert_eq!(
876 invalid_key(&with(
877 "\n[lanes.other]\nharness = \"claude\"\nmodel = \"opus\"\nprovider = \"openai\""
878 )),
879 "lanes.other.provider"
880 );
881 }
882
883 #[test]
884 fn a_lane_needs_a_model() {
885 let text = BASE.replace("model = \"deepseek-flash\"\n", "");
886
887 assert_eq!(invalid_key(&text), "lanes.deepseek.model");
888 }
889
890 #[test]
891 fn effort_must_be_a_known_level() {
892 let bad = BASE.replacen(
893 "model = \"sonnet\"",
894 "model = \"sonnet\"\neffort = \"extreme\"",
895 1,
896 );
897 assert_eq!(invalid_key(&bad), "lanes.plan.effort");
898
899 let ok = BASE.replacen(
900 "model = \"sonnet\"",
901 "model = \"sonnet\"\neffort = \"xhigh\"\nultracode = true",
902 1,
903 );
904 let cfg = parse(&ok, false).unwrap();
905 assert_eq!(cfg.lanes["plan"].effort, Effort::Xhigh);
906 assert!(cfg.lanes["plan"].ultracode);
907 }
908
909 #[test]
910 fn an_agy_lane_is_manual_unless_told_otherwise() {
911 let config = parse(&with_gemini(""), false).unwrap();
912
913 assert_eq!(config.lanes["gemini"].mode, Mode::Handover);
914 assert_eq!(
915 invalid_key(&with_gemini("mode = \"auto\"")),
916 "lanes.gemini.mode"
917 );
918 }
919
920 #[test]
921 fn direct_agy_needs_the_risk_acknowledgement_and_a_quota_group() {
922 let no_ack = with_gemini("mode = \"direct\"\nquota_group = \"Gemini Models\"");
923 let no_group = with_gemini("mode = \"direct\"\naccept_vendor_terms_risk = true");
924 let both =
925 with_gemini("mode = \"direct\"\nquota_group = \"G\"\naccept_vendor_terms_risk = true");
926
927 assert_eq!(
928 invalid_key(&no_ack),
929 "lanes.gemini.accept_vendor_terms_risk"
930 );
931 assert_eq!(invalid_key(&no_group), "lanes.gemini.quota_group");
932 assert_eq!(
933 parse(&both, false).unwrap().lanes["gemini"].mode,
934 Mode::Direct
935 );
936 }
937
938 #[test]
939 fn fake_lanes_need_the_test_switch_and_a_script() {
940 let fake = BASE.replace(
941 "harness = \"codex\"\nmodel = \"deepseek-flash\"",
942 "harness = \"fake\"\nscript = \"s.json\"",
943 );
944 let no_script = BASE.replace(
945 "harness = \"codex\"\nmodel = \"deepseek-flash\"",
946 "harness = \"fake\"",
947 );
948
949 assert_eq!(invalid_key(&fake), "lanes.deepseek.harness");
950 assert_eq!(
951 parse(&fake, true).unwrap().lanes["deepseek"].script,
952 Some(PathBuf::from("s.json"))
953 );
954 assert!(
955 matches!(parse(&no_script, true), Err(ConfigError::Invalid { key, .. }) if key == "lanes.deepseek.script")
956 );
957 }
958
959 #[test]
960 fn a_fake_lane_may_serve_every_role() {
961 let text = r#"
962[roles]
963planner = ["f"]
964reviewer = ["f"]
965worker = ["f"]
966
967[lanes.f]
968harness = "fake"
969script = "s.json"
970"#;
971
972 assert!(parse(text, true).is_ok());
973 }
974
975 #[test]
976 fn planner_and_reviewer_accept_automatic_chains_and_reject_manual_or_off() {
977 let empty = BASE.replace(r#"planner = ["plan"]"#, "planner = []");
978 let dup = BASE.replace(r#"planner = ["plan"]"#, r#"planner = ["plan", "plan"]"#);
979 let two = BASE.replace(r#"planner = ["plan"]"#, r#"planner = ["plan", "review"]"#);
980 let unknown = BASE.replace(r#"reviewer = ["review"]"#, r#"reviewer = ["nobody"]"#);
981 let worker_as_reviewer =
982 BASE.replace(r#"reviewer = ["review"]"#, r#"reviewer = ["deepseek"]"#);
983 let manual_planner =
984 with_gemini("").replace(r#"planner = ["plan"]"#, r#"planner = ["gemini"]"#);
985 let off_reviewer = with_gemini("mode = \"off\"")
986 .replace(r#"reviewer = ["review"]"#, r#"reviewer = ["gemini"]"#);
987 let direct_agy_planner =
988 with_gemini("mode = \"direct\"\nquota_group = \"G\"\naccept_vendor_terms_risk = true")
989 .replace(r#"planner = ["plan"]"#, r#"planner = ["gemini"]"#);
990
991 assert_eq!(invalid_key(&empty), "roles.planner");
992 assert_eq!(invalid_key(&dup), "roles.planner");
993 assert_eq!(
994 parse(&two, false).unwrap().roles.planner,
995 ["plan", "review"]
996 );
997 assert_eq!(invalid_key(&unknown), "roles.reviewer");
998 assert_eq!(
999 parse(&worker_as_reviewer, false).unwrap().roles.reviewer,
1000 ["deepseek"]
1001 );
1002 assert_eq!(invalid_key(&manual_planner), "roles.planner");
1003 assert_eq!(invalid_key(&off_reviewer), "roles.reviewer");
1004 assert_eq!(
1005 parse(&direct_agy_planner, false).unwrap().roles.planner,
1006 ["gemini"]
1007 );
1008 }
1009
1010 #[test]
1011 fn the_worker_chain_accepts_any_distinct_lanes_with_one_not_off() {
1012 let empty = BASE.replace(r#"worker = ["deepseek"]"#, "worker = []");
1013 let twice = BASE.replace(
1014 r#"worker = ["deepseek"]"#,
1015 r#"worker = ["deepseek", "deepseek"]"#,
1016 );
1017 let claude = BASE.replace(r#"worker = ["deepseek"]"#, r#"worker = ["plan"]"#);
1018 let all_off = with_gemini("mode = \"off\"").replace(
1019 r#"worker = ["deepseek", "gemini"]"#,
1020 r#"worker = ["gemini"]"#,
1021 );
1022
1023 for text in [empty, twice, all_off] {
1024 assert_eq!(invalid_key(&text), "roles.worker");
1025 }
1026 assert_eq!(parse(&claude, false).unwrap().roles.worker, ["plan"]);
1027 }
1028
1029 #[test]
1030 fn codex_provider_defaults_to_deepseek_and_accepts_openai() {
1031 let openai =
1032 with("\n[lanes.gpt]\nharness = \"codex\"\nprovider = \"openai\"\nmodel = \"gpt-5.4\"")
1033 .replace(
1034 r#"worker = ["deepseek"]"#,
1035 r#"worker = ["deepseek", "gpt"]"#,
1036 );
1037 let bad = with("provider = \"anthropic\"");
1038
1039 let config = parse(&openai, false).unwrap();
1040
1041 assert_eq!(
1042 config.lanes["deepseek"].provider,
1043 Some(CodexProvider::Deepseek)
1044 );
1045 assert_eq!(config.lanes["gpt"].provider, Some(CodexProvider::Openai));
1046 assert_eq!(invalid_key(&bad), "lanes.deepseek.provider");
1047 }
1048
1049 #[test]
1050 fn to_toml_and_save_round_trip_every_harness_cleanly() {
1051 let mut config = parse(EXAMPLE, false).unwrap();
1052 config.run.idle_timeout = Duration::from_secs(3600);
1053 config.run.job_timeout = Duration::from_secs(61);
1054 let openai_lane = Lane {
1055 harness: HarnessKind::Codex,
1056 bin: "/usr/local/bin/codex".into(),
1057 provider: Some(CodexProvider::Openai),
1058 model: Some("gpt-5.4".into()),
1059 effort: Effort::Medium,
1060 ultracode: false,
1061 mode: Mode::Direct,
1062 quota_group: None,
1063 accept_vendor_terms_risk: false,
1064 script: None,
1065 };
1066 config.lanes.insert("openai".into(), openai_lane);
1067 config.roles.worker.push("openai".into());
1068 let opencode_lane = Lane {
1069 harness: HarnessKind::OpenCode,
1070 bin: "opencode".into(),
1071 provider: None,
1072 model: Some("opencode-go/deepseek-v4.1-flash".into()),
1073 effort: Effort::Medium,
1074 ultracode: false,
1075 mode: Mode::Direct,
1076 quota_group: None,
1077 accept_vendor_terms_risk: false,
1078 script: None,
1079 };
1080 config.lanes.insert("opencode".into(), opencode_lane);
1081 config.roles.worker.push("opencode".into());
1082
1083 config.lanes.get_mut("plan").unwrap().effort = Effort::Xhigh;
1084 config.lanes.get_mut("plan").unwrap().ultracode = true;
1085 config.lanes.get_mut("review").unwrap().effort = Effort::Max;
1086 let dir = tempfile::tempdir().unwrap();
1087 let path = dir.path().join("nested").join("config.toml");
1088 save(&path, &config).unwrap();
1089 let text = std::fs::read_to_string(&path).unwrap();
1090 assert!(text.contains("ultracode = true"));
1091 assert!(text.contains("idle_timeout = \"1h\""));
1092 assert!(text.contains("job_timeout = \"61s\""));
1093 assert!(!text.contains("bin = \"codex\""));
1094 let reloaded = load(&path, false).unwrap();
1095
1096 assert_eq!(reloaded, config);
1097 assert_eq!(format_duration(Duration::from_secs(3601)), "3601s");
1098 assert_eq!(format_duration(Duration::from_secs(60)), "1m");
1099 }
1100
1101 #[test]
1102 fn the_error_message_names_the_key_and_the_fix() {
1103 let error = parse(&with("\n[run]\nmax_attempts = 0"), false).unwrap_err();
1104
1105 assert_eq!(
1106 error.to_string(),
1107 "run.max_attempts: use a number from 1 to 20"
1108 );
1109 }
1110
1111 #[test]
1112 fn load_reports_a_missing_file_with_its_path() {
1113 let dir = tempfile::tempdir().unwrap();
1114 let path = dir.path().join("config.toml");
1115
1116 assert_eq!(load(&path, false), Err(ConfigError::Missing(path.clone())));
1117 std::fs::write(&path, BASE).unwrap();
1118 assert!(load(&path, false).is_ok());
1119 }
1120
1121 #[test]
1122 fn the_default_path_prefers_xdg_and_falls_back_to_home() {
1123 assert_eq!(
1124 default_path(Some("/x"), Some("/h")),
1125 Some(PathBuf::from("/x/onerig/config.toml"))
1126 );
1127 assert_eq!(
1128 default_path(Some(""), Some("/h")),
1129 Some(PathBuf::from("/h/.config/onerig/config.toml"))
1130 );
1131 assert_eq!(
1132 default_path(None, Some("/h")),
1133 Some(PathBuf::from("/h/.config/onerig/config.toml"))
1134 );
1135 assert_eq!(default_path(None, None), None);
1136 }
1137}