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