harnesscli 0.1.6

Unified CLI to run Claude Code, OpenCode, Codex, or Cursor from a single interface
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::config::AgentKind;
use crate::models::{ModelEntry, ModelRegistry};

/// User settings loaded from `~/.config/harness/config.toml` and optionally
/// merged with a project-level `.harnessrc.toml`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Settings {
    /// Default agent to use if `--agent` is omitted.
    #[serde(default)]
    pub default_agent: Option<String>,

    /// Default model to use if `--model` is omitted.
    #[serde(default)]
    pub default_model: Option<String>,

    /// Default permission mode (`full-access` or `read-only`).
    #[serde(default)]
    pub default_permissions: Option<String>,

    /// Default timeout in seconds.
    #[serde(default)]
    pub default_timeout_secs: Option<u64>,

    /// Log level for tracing output (e.g. "debug", "info", "warn").
    #[serde(default)]
    pub log_level: Option<String>,

    /// Per-agent configuration overrides.
    #[serde(default)]
    pub agents: HashMap<String, AgentSettings>,
}

/// Per-agent settings.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AgentSettings {
    /// Override binary path for this agent.
    #[serde(default)]
    pub binary: Option<String>,

    /// Default model for this agent.
    #[serde(default)]
    pub model: Option<String>,

    /// Extra args always prepended for this agent.
    #[serde(default)]
    pub extra_args: Vec<String>,
}

impl Settings {
    /// Load settings from the default config file, optionally merged with a
    /// project-level `.harnessrc.toml` found by walking up from `cwd`.
    pub fn load() -> Self {
        Self::load_from(Self::config_path())
    }

    /// Load global settings, then merge project-level overrides from `cwd`.
    pub fn load_with_project(cwd: Option<&Path>) -> Self {
        let global = Self::load();
        if let Some(dir) = cwd {
            if let Some(project) = Self::load_project(dir) {
                return global.merge(&project);
            }
        }
        global
    }

    /// Load settings from a specific path.
    pub fn load_from(path: Option<PathBuf>) -> Self {
        let Some(path) = path else {
            return Self::default();
        };

        if !path.exists() {
            return Self::default();
        }

        let content = match std::fs::read_to_string(&path) {
            Ok(c) => c,
            Err(e) => {
                tracing::warn!("failed to read config file {}: {e}", path.display());
                return Self::default();
            }
        };

        match toml::from_str(&content) {
            Ok(s) => s,
            Err(e) => {
                tracing::warn!("failed to parse config file {}: {e}", path.display());
                Self::default()
            }
        }
    }

    /// Walk up from `start` looking for `.harnessrc.toml`. Returns the parsed
    /// settings if found, `None` otherwise.
    pub fn load_project(start: &Path) -> Option<Self> {
        let mut dir = start.to_path_buf();
        loop {
            let candidate = dir.join(".harnessrc.toml");
            if candidate.exists() {
                return Some(Self::load_from(Some(candidate)));
            }
            if !dir.pop() {
                break;
            }
        }
        None
    }

    /// Merge another settings into this one. `other` (project) wins for scalar
    /// fields; `extra_args` in agent settings are concatenated.
    pub fn merge(&self, other: &Settings) -> Settings {
        let mut merged = self.clone();

        if other.default_agent.is_some() {
            merged.default_agent.clone_from(&other.default_agent);
        }
        if other.default_model.is_some() {
            merged.default_model.clone_from(&other.default_model);
        }
        if other.default_permissions.is_some() {
            merged
                .default_permissions
                .clone_from(&other.default_permissions);
        }
        if other.default_timeout_secs.is_some() {
            merged.default_timeout_secs = other.default_timeout_secs;
        }
        if other.log_level.is_some() {
            merged.log_level.clone_from(&other.log_level);
        }

        // Merge per-agent settings.
        for (key, other_agent) in &other.agents {
            let entry = merged
                .agents
                .entry(key.clone())
                .or_default();
            if other_agent.binary.is_some() {
                entry.binary.clone_from(&other_agent.binary);
            }
            if other_agent.model.is_some() {
                entry.model.clone_from(&other_agent.model);
            }
            // Concatenate extra_args (global first, then project).
            if !other_agent.extra_args.is_empty() {
                entry.extra_args.extend(other_agent.extra_args.clone());
            }
        }

        merged
    }

    /// Default config file path: `~/.config/harness/config.toml`.
    pub fn config_path() -> Option<PathBuf> {
        dirs::config_dir().map(|d| d.join("harness").join("config.toml"))
    }

    /// Generate a template config file as a TOML string.
    pub fn template() -> &'static str {
        r#"# harness configuration — ~/.config/harness/config.toml

# Default agent when --agent is omitted.
# default_agent = "claude"

# Default model when --model is omitted.
# default_model = "claude-opus-4-6"

# Default permission mode: "full-access" or "read-only".
# default_permissions = "full-access"

# Default timeout in seconds.
# default_timeout_secs = 300

# Log level: "error", "warn", "info", "debug", "trace".
# log_level = "warn"

# Per-agent settings.
# [agents.claude]
# binary = "/opt/claude/bin/claude"
# model = "claude-opus-4-6"
# extra_args = ["--verbose"]

# [agents.codex]
# model = "gpt-5-codex"
# extra_args = []
"#
    }

    /// Resolve the default agent from settings.
    pub fn resolve_default_agent(&self) -> Option<AgentKind> {
        self.default_agent.as_ref()?.parse().ok()
    }

    /// Get agent-specific settings.
    pub fn agent_settings(&self, kind: AgentKind) -> Option<&AgentSettings> {
        let key = match kind {
            AgentKind::Claude => "claude",
            AgentKind::OpenCode => "opencode",
            AgentKind::Codex => "codex",
            AgentKind::Cursor => "cursor",
        };
        self.agents.get(key)
    }

    /// Resolve the binary path for a given agent from settings.
    pub fn agent_binary(&self, kind: AgentKind) -> Option<PathBuf> {
        self.agent_settings(kind)
            .and_then(|s| s.binary.as_ref())
            .map(PathBuf::from)
    }

    /// Resolve the model for a given agent from settings.
    pub fn agent_model(&self, kind: AgentKind) -> Option<String> {
        // Agent-specific model takes precedence over global default.
        self.agent_settings(kind)
            .and_then(|s| s.model.clone())
            .or_else(|| self.default_model.clone())
    }

    /// Get agent-specific extra_args from settings.
    pub fn agent_extra_args(&self, kind: AgentKind) -> Vec<String> {
        self.agent_settings(kind)
            .map(|s| s.extra_args.clone())
            .unwrap_or_default()
    }
}

/// Project-level configuration loaded from `harness.toml` in the project directory.
///
/// This is the new config format — replaces `~/.config/harness/config.toml` (global)
/// and `.harnessrc.toml` (walk-up). Contains the same fields as `Settings` plus a
/// `[models]` section for project-level model overrides.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ProjectConfig {
    #[serde(default)]
    pub default_agent: Option<String>,

    #[serde(default)]
    pub default_model: Option<String>,

    #[serde(default)]
    pub default_permissions: Option<String>,

    #[serde(default)]
    pub default_timeout_secs: Option<u64>,

    #[serde(default)]
    pub log_level: Option<String>,

    /// Per-agent configuration overrides.
    #[serde(default)]
    pub agents: HashMap<String, AgentSettings>,

    /// Project-level model overrides / additions.
    #[serde(default)]
    pub models: HashMap<String, ModelEntry>,
}

impl ProjectConfig {
    /// Load `harness.toml` by walking up from `dir` to find the nearest one.
    pub fn load(dir: &Path) -> Option<Self> {
        let (config, _path) = Self::load_with_path(dir)?;
        Some(config)
    }

    /// Load `harness.toml` by walking up from `dir`, returning both the config
    /// and the path where it was found.
    pub fn load_with_path(dir: &Path) -> Option<(Self, PathBuf)> {
        let mut current = dir.to_path_buf();
        loop {
            let path = current.join("harness.toml");
            if path.exists() {
                let content = match std::fs::read_to_string(&path) {
                    Ok(c) => c,
                    Err(e) => {
                        tracing::warn!("failed to read {}: {e}", path.display());
                        return None;
                    }
                };
                return match toml::from_str(&content) {
                    Ok(c) => Some((c, path)),
                    Err(e) => {
                        tracing::warn!("failed to parse {}: {e}", path.display());
                        None
                    }
                };
            }
            if !current.pop() {
                break;
            }
        }
        None
    }

    /// Extract the `[models]` section as a `ModelRegistry`.
    pub fn model_registry(&self) -> ModelRegistry {
        ModelRegistry {
            models: self.models.clone(),
        }
    }

    /// Resolve the default agent from this config.
    pub fn resolve_default_agent(&self) -> Option<AgentKind> {
        self.default_agent.as_ref()?.parse().ok()
    }

    /// Get agent-specific settings.
    pub fn agent_settings(&self, kind: AgentKind) -> Option<&AgentSettings> {
        let key = match kind {
            AgentKind::Claude => "claude",
            AgentKind::OpenCode => "opencode",
            AgentKind::Codex => "codex",
            AgentKind::Cursor => "cursor",
        };
        self.agents.get(key)
    }

    /// Resolve the binary path for a given agent.
    pub fn agent_binary(&self, kind: AgentKind) -> Option<PathBuf> {
        self.agent_settings(kind)
            .and_then(|s| s.binary.as_ref())
            .map(PathBuf::from)
    }

    /// Resolve the model for a given agent.
    pub fn agent_model(&self, kind: AgentKind) -> Option<String> {
        self.agent_settings(kind)
            .and_then(|s| s.model.clone())
            .or_else(|| self.default_model.clone())
    }

    /// Get agent-specific extra_args.
    pub fn agent_extra_args(&self, kind: AgentKind) -> Vec<String> {
        self.agent_settings(kind)
            .map(|s| s.extra_args.clone())
            .unwrap_or_default()
    }

    /// Generate a template `harness.toml` file.
    pub fn template() -> &'static str {
        r#"# harness project configuration — harness.toml
#
# Place this file in your project root.

# Default agent when --agent is omitted.
# default_agent = "claude"

# Default model when --model is omitted (uses model registry for translation).
# default_model = "sonnet"

# Default permission mode: "full-access" or "read-only".
# default_permissions = "full-access"

# Default timeout in seconds.
# default_timeout_secs = 300

# Log level: "error", "warn", "info", "debug", "trace".
# log_level = "warn"

# Per-agent settings.
# [agents.claude]
# binary = "/opt/claude/bin/claude"
# model = "sonnet"
# extra_args = ["--verbose"]

# Model registry overrides.
# These override or extend the canonical registry for this project.
# [models.my-model]
# description = "My custom model"
# provider = "anthropic"
# claude = "my-custom-model-id"
"#
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_empty_config() {
        let settings: Settings = toml::from_str("").unwrap();
        assert!(settings.default_agent.is_none());
        assert!(settings.agents.is_empty());
    }

    #[test]
    fn parse_full_config() {
        let toml = r#"
default_agent = "claude"
default_model = "claude-opus-4-6"

[agents.claude]
binary = "/opt/claude/bin/claude"

[agents.codex]
model = "gpt-5-codex"
"#;
        let settings: Settings = toml::from_str(toml).unwrap();
        assert_eq!(settings.default_agent, Some("claude".to_string()));
        assert_eq!(settings.default_model, Some("claude-opus-4-6".to_string()));
        assert_eq!(
            settings.agents["claude"].binary,
            Some("/opt/claude/bin/claude".to_string())
        );
        assert_eq!(
            settings.agents["codex"].model,
            Some("gpt-5-codex".to_string())
        );
    }

    #[test]
    fn parse_expanded_config() {
        let toml = r#"
default_agent = "claude"
default_model = "opus"
default_permissions = "read-only"
default_timeout_secs = 300
log_level = "debug"

[agents.claude]
binary = "/usr/bin/claude"
model = "sonnet"
extra_args = ["--verbose", "--no-color"]
"#;
        let settings: Settings = toml::from_str(toml).unwrap();
        assert_eq!(settings.default_permissions, Some("read-only".into()));
        assert_eq!(settings.default_timeout_secs, Some(300));
        assert_eq!(settings.log_level, Some("debug".into()));
        let claude = settings.agent_settings(AgentKind::Claude).unwrap();
        assert_eq!(claude.extra_args, vec!["--verbose", "--no-color"]);
    }

    #[test]
    fn resolve_default_agent() {
        let settings = Settings {
            default_agent: Some("claude".to_string()),
            ..Default::default()
        };
        assert_eq!(settings.resolve_default_agent(), Some(AgentKind::Claude));
    }

    #[test]
    fn agent_model_prefers_specific() {
        let mut agents = HashMap::new();
        agents.insert(
            "claude".to_string(),
            AgentSettings {
                model: Some("sonnet".to_string()),
                ..Default::default()
            },
        );
        let settings = Settings {
            default_model: Some("opus".to_string()),
            agents,
            ..Default::default()
        };
        assert_eq!(
            settings.agent_model(AgentKind::Claude),
            Some("sonnet".to_string())
        );
        assert_eq!(
            settings.agent_model(AgentKind::Codex),
            Some("opus".to_string())
        );
    }

    #[test]
    fn load_nonexistent_returns_default() {
        let settings = Settings::load_from(Some(PathBuf::from("/nonexistent/path/config.toml")));
        assert!(settings.default_agent.is_none());
    }

    #[test]
    fn merge_project_overrides() {
        let global = Settings {
            default_agent: Some("claude".into()),
            default_model: Some("opus".into()),
            default_timeout_secs: Some(300),
            ..Default::default()
        };
        let project = Settings {
            default_model: Some("sonnet".into()),
            default_permissions: Some("read-only".into()),
            ..Default::default()
        };
        let merged = global.merge(&project);
        assert_eq!(merged.default_agent, Some("claude".into())); // kept from global
        assert_eq!(merged.default_model, Some("sonnet".into())); // overridden by project
        assert_eq!(merged.default_timeout_secs, Some(300)); // kept from global
        assert_eq!(merged.default_permissions, Some("read-only".into())); // from project
    }

    #[test]
    fn merge_agent_extra_args_concatenate() {
        let mut global_agents = HashMap::new();
        global_agents.insert(
            "claude".to_string(),
            AgentSettings {
                extra_args: vec!["--verbose".into()],
                ..Default::default()
            },
        );
        let global = Settings {
            agents: global_agents,
            ..Default::default()
        };

        let mut project_agents = HashMap::new();
        project_agents.insert(
            "claude".to_string(),
            AgentSettings {
                extra_args: vec!["--no-color".into()],
                model: Some("sonnet".into()),
                ..Default::default()
            },
        );
        let project = Settings {
            agents: project_agents,
            ..Default::default()
        };

        let merged = global.merge(&project);
        let claude = merged.agent_settings(AgentKind::Claude).unwrap();
        assert_eq!(claude.extra_args, vec!["--verbose", "--no-color"]);
        assert_eq!(claude.model, Some("sonnet".into()));
    }

    #[test]
    fn load_project_walks_up() {
        let tmp = tempfile::tempdir().unwrap();
        let deep = tmp.path().join("a").join("b").join("c");
        std::fs::create_dir_all(&deep).unwrap();

        // Place .harnessrc.toml at `a/` level.
        let rc_path = tmp.path().join("a").join(".harnessrc.toml");
        std::fs::write(&rc_path, "default_agent = \"codex\"\n").unwrap();

        // Starting from `a/b/c`, should find `a/.harnessrc.toml`.
        let found = Settings::load_project(&deep);
        assert!(found.is_some());
        assert_eq!(found.unwrap().default_agent, Some("codex".into()));
    }

    #[test]
    fn agent_extra_args_from_settings() {
        let mut agents = HashMap::new();
        agents.insert(
            "claude".to_string(),
            AgentSettings {
                extra_args: vec!["--verbose".into()],
                ..Default::default()
            },
        );
        let settings = Settings {
            agents,
            ..Default::default()
        };
        assert_eq!(
            settings.agent_extra_args(AgentKind::Claude),
            vec!["--verbose"]
        );
        assert!(settings.agent_extra_args(AgentKind::Codex).is_empty());
    }

    #[test]
    fn template_parses_as_valid_toml() {
        // The template should parse (all lines are commented out).
        let result: std::result::Result<Settings, _> = toml::from_str(Settings::template());
        assert!(result.is_ok());
    }

    // ─── ProjectConfig tests ─────────────────────────────────────

    #[test]
    fn project_config_parse_empty() {
        let config: ProjectConfig = toml::from_str("").unwrap();
        assert!(config.default_agent.is_none());
        assert!(config.models.is_empty());
    }

    #[test]
    fn project_config_parse_with_models() {
        let toml = r#"
default_agent = "claude"
default_model = "sonnet"

[agents.claude]
binary = "/usr/bin/claude"

[models.my-model]
description = "Custom"
provider = "custom"
claude = "custom-id"
"#;
        let config: ProjectConfig = toml::from_str(toml).unwrap();
        assert_eq!(config.default_agent, Some("claude".into()));
        assert_eq!(config.default_model, Some("sonnet".into()));
        assert!(config.models.contains_key("my-model"));
        assert_eq!(
            config.models["my-model"].claude,
            Some("custom-id".into())
        );
    }

    #[test]
    fn project_config_model_registry() {
        let toml = r#"
[models.test]
description = "Test"
provider = "test"
claude = "test-id"
"#;
        let config: ProjectConfig = toml::from_str(toml).unwrap();
        let reg = config.model_registry();
        assert!(reg.models.contains_key("test"));
    }

    #[test]
    fn project_config_load_from_dir() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(
            tmp.path().join("harness.toml"),
            "default_agent = \"claude\"\n",
        )
        .unwrap();
        let config = ProjectConfig::load(tmp.path());
        assert!(config.is_some());
        assert_eq!(config.unwrap().default_agent, Some("claude".into()));
    }

    #[test]
    fn project_config_load_walks_up() {
        let tmp = tempfile::tempdir().unwrap();
        let deep = tmp.path().join("a").join("b").join("c");
        std::fs::create_dir_all(&deep).unwrap();

        // Place harness.toml at `a/` level.
        std::fs::write(
            tmp.path().join("a").join("harness.toml"),
            "default_agent = \"codex\"\n",
        )
        .unwrap();

        // Starting from `a/b/c`, should find `a/harness.toml`.
        let config = ProjectConfig::load(&deep);
        assert!(config.is_some());
        assert_eq!(config.unwrap().default_agent, Some("codex".into()));
    }

    #[test]
    fn project_config_load_missing_returns_none() {
        let tmp = tempfile::tempdir().unwrap();
        assert!(ProjectConfig::load(tmp.path()).is_none());
    }

    #[test]
    fn project_config_template_parses() {
        let result: std::result::Result<ProjectConfig, _> =
            toml::from_str(ProjectConfig::template());
        assert!(result.is_ok());
    }
}