thirdshift 0.13.0

Turn a GitHub issue into a ready-for-review pull request, unattended
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
//! The Harness a Command's agent sessions run on, with its Model and Effort:
//! one [`Choice`] per Command, made by the command, else the User config,
//! else the default, checked before any work, passed on to every session and
//! child Run, and recorded with what the Command did.

use std::fmt;
use std::path::Path;
use std::process::Output;

use anyhow::{Result, bail};

mod adapter;
pub(crate) mod agy;
pub(crate) mod claude;
pub(crate) mod codex;
pub(crate) mod grok;
mod instructions;
pub(crate) mod interpretation;
#[cfg(test)]
pub(crate) mod interpretation_tests;
pub(crate) mod muse;
pub(crate) mod opencode;
pub(crate) mod process;
pub(crate) mod settings;
mod skill_load;
mod summary;

pub use adapter::Adapter;
pub use summary::write as write_summary;

/// The headless agent CLI a Command's sessions run on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Harness {
    Claude,
    Codex,
    Agy,
    Grok,
    Muse,
    OpenCode,
}

impl Harness {
    /// The Harness named `name`, as the command line and the User config
    /// write it, if it is one.
    pub fn named(name: &str) -> Option<Harness> {
        adapter::REGISTERED
            .iter()
            .find(|(_, adapter)| adapter.name() == name)
            .map(|(harness, _)| *harness)
    }

    /// Its name, which is also its CLI's.
    pub fn name(self) -> &'static str {
        self.adapter().name()
    }

    /// Select the adapter once; session callers retain it for their lifetime.
    pub fn adapter(self) -> &'static dyn Adapter {
        adapter::REGISTERED
            .iter()
            .find(|(harness, _)| *harness == self)
            .map(|(_, adapter)| *adapter)
            .expect("every Harness has an adapter")
    }

    /// Every Harness, in the order its adapters register for Setup.
    pub const ALL: [Harness; adapter::REGISTERED.len()] = {
        let mut all = [adapter::REGISTERED[0].0; adapter::REGISTERED.len()];
        let mut at = 0;
        while at < all.len() {
            all[at] = adapter::REGISTERED[at].0;
            at += 1;
        }
        all
    };

    /// Whether sessions can run on it here: its CLI is on `PATH`.
    pub fn installed(self) -> bool {
        on_path(self.name())
    }
}

/// The names a Harness is chosen by, for the messages that list them.
pub fn names() -> String {
    adapter::REGISTERED
        .iter()
        .map(|(_, adapter)| adapter.name())
        .collect::<Vec<_>>()
        .join(" or ")
}

/// A Model and an Effort, each none where it is left to the Harness.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ModelAndEffort {
    pub model: Option<String>,
    pub effort: Option<String>,
}

/// The User config's `[harness]` section: the default Harness, if it names
/// one, and a Model and Effort for each Harness.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Settings {
    /// `harness.default`.
    pub default: Option<Harness>,
    /// `[harness.claude]`.
    pub claude: ModelAndEffort,
    /// `[harness.codex]`.
    pub codex: ModelAndEffort,
    /// `[harness.agy]`.
    pub agy: ModelAndEffort,
    /// `[harness.grok]`.
    pub grok: ModelAndEffort,
    /// `[harness.muse]`.
    pub muse: ModelAndEffort,
    /// `[harness.opencode]`.
    pub opencode: ModelAndEffort,
}

impl Settings {
    /// The Model and Effort set for `harness`.
    pub fn of(&self, harness: Harness) -> &ModelAndEffort {
        harness.adapter().settings(self)
    }

    /// The Model and Effort set for `harness`, to set them.
    pub fn of_mut(&mut self, harness: Harness) -> &mut ModelAndEffort {
        harness.adapter().settings_mut(self)
    }
}

/// What a command asked for, each none if it said nothing about it.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Asked {
    /// What `harness <name>` asked for.
    pub harness: Option<Harness>,
    /// What `model <name>` and `effort <level>` asked for.
    pub model_and_effort: ModelAndEffort,
}

/// What chose the Harness, for a failure to name.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChosenBy {
    /// The command's `harness` flag, or for a child Run, the command that
    /// started it.
    Command,
    /// The User config's `harness.default`.
    UserConfig,
    /// The User config's `security.harness`.
    SecurityConfig,
    /// Neither: Claude Code, the default.
    Default,
}

/// The Harness, Model and Effort every session of a Command runs on.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Choice {
    pub harness: Harness,
    /// The Model, or none to leave it to the Harness.
    pub model: Option<String>,
    /// The Effort, or none to leave it to the Harness.
    pub effort: Option<String>,
    pub chosen_by: ChosenBy,
}

impl Default for Choice {
    /// Claude Code, with its own Model and Effort: a Command's sessions with
    /// nothing asked and nothing set.
    fn default() -> Self {
        Choice {
            harness: Harness::Claude,
            model: None,
            effort: None,
            chosen_by: ChosenBy::Default,
        }
    }
}

impl Choice {
    /// What a command that `asked` for it runs on, given the User config's
    /// `settings`: for each of the Harness, Model and Effort, what the
    /// command asked, else what the User config sets, else the default. The
    /// Model and Effort it sets are those of the Harness chosen.
    pub fn of(asked: &Asked, settings: &Settings) -> Choice {
        let (harness, chosen_by) = match (asked.harness, settings.default) {
            (Some(harness), _) => (harness, ChosenBy::Command),
            (None, Some(harness)) => (harness, ChosenBy::UserConfig),
            (None, None) => (Harness::Claude, ChosenBy::Default),
        };
        let set = settings.of(harness);
        let asked = &asked.model_and_effort;
        Choice {
            harness,
            model: asked.model.clone().or_else(|| set.model.clone()),
            effort: asked.effort.clone().or_else(|| set.effort.clone()),
            chosen_by,
        }
    }

    /// The line thirdshift writes in a pull request's body and a Run
    /// notification, as in `Built with claude · claude-opus-5-5 · high`.
    pub fn built_with(&self) -> String {
        format!("Built with {self}")
    }

    // Compatibility for the existing argument tests; production callers
    // use the adapter's complete session invocation.
    #[cfg(test)]
    pub fn claude_args(&self) -> Vec<&str> {
        claude::model_args(self)
    }
    #[cfg(test)]
    pub fn codex_args(&self) -> Vec<String> {
        codex::model_args(self)
    }

    /// Check, before any work, that the CLI is on `PATH`, then settle the
    /// Model and Effort through its adapter's catalog or minimal test call.
    /// Each failure says what to change.
    pub fn check(&mut self) -> Result<()> {
        let adapter = self.harness.adapter();
        let cli = adapter.name();
        if !on_path(cli) {
            bail!(
                "{cli} is not on PATH, and the Harness {cli} is chosen by {}: install it, \
                 or choose another Harness",
                self.chosen_by
            );
        }
        adapter.check(self)
    }
}

/// What a CLI said on stderr and stdout, trimmed, each on its own lines.
fn said(output: &Output) -> String {
    [&output.stderr, &output.stdout]
        .map(|said| String::from_utf8_lossy(said).trim().to_string())
        .into_iter()
        .filter(|said| !said.is_empty())
        .collect::<Vec<_>>()
        .join("\n")
}

impl fmt::Display for Choice {
    /// `<harness> · <model> · <effort>`, as in `claude · claude-opus-5-5 ·
    /// high`, saying `default model` or `default effort` for one left to the
    /// Harness.
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{} · {} · {}",
            self.harness.name(),
            self.model.as_deref().unwrap_or("default model"),
            self.effort.as_deref().unwrap_or("default effort")
        )
    }
}

impl fmt::Display for ChosenBy {
    /// The setting that chose the Harness, as a failure names it.
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(match self {
            ChosenBy::Command => "the harness flag",
            ChosenBy::UserConfig => "harness.default in the User config",
            ChosenBy::SecurityConfig => "security.harness in the User config",
            ChosenBy::Default => {
                "the default, as neither the harness flag nor harness.default in the User \
                 config names one"
            }
        })
    }
}

/// Whether an executable file named `cli` is in a directory on `PATH`.
fn on_path(cli: &str) -> bool {
    use std::os::unix::fs::PermissionsExt;
    let Some(path) = std::env::var_os("PATH") else {
        return false;
    };
    std::env::split_paths(&path).any(|dir| {
        Path::new(&dir)
            .join(cli)
            .metadata()
            .is_ok_and(|file| file.is_file() && file.permissions().mode() & 0o111 != 0)
    })
}

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

    fn set(model: &str, effort: &str) -> ModelAndEffort {
        let named = |value: &str| (!value.is_empty()).then(|| value.to_string());
        ModelAndEffort {
            model: named(model),
            effort: named(effort),
        }
    }

    /// A User config whose default is Codex, with a Model and Effort for
    /// each Harness.
    fn codex_default() -> Settings {
        Settings {
            default: Some(Harness::Codex),
            claude: set("opus", "high"),
            codex: set("gpt-6.1-sol", "max"),
            ..Settings::default()
        }
    }

    fn choice(harness: Harness, model: &str, effort: &str, chosen_by: ChosenBy) -> Choice {
        let set = set(model, effort);
        Choice {
            harness,
            model: set.model,
            effort: set.effort,
            chosen_by,
        }
    }

    #[test]
    fn with_nothing_asked_and_nothing_set_sessions_run_on_claude_with_its_own_model_and_effort() {
        let chosen = Choice::of(&Asked::default(), &Settings::default());

        assert_eq!(chosen, Choice::default());
        assert!(chosen.claude_args().is_empty());
    }

    #[test]
    fn the_user_config_chooses_the_harness_and_its_own_model_and_effort() {
        let chosen = Choice::of(&Asked::default(), &codex_default());

        assert_eq!(
            chosen,
            choice(Harness::Codex, "gpt-6.1-sol", "max", ChosenBy::UserConfig)
        );
    }

    #[test]
    fn a_harness_on_the_command_takes_that_harnesss_model_and_effort_from_the_user_config() {
        let asked = Asked {
            harness: Some(Harness::Claude),
            ..Asked::default()
        };

        let chosen = Choice::of(&asked, &codex_default());

        assert_eq!(
            chosen,
            choice(Harness::Claude, "opus", "high", ChosenBy::Command)
        );
    }

    #[test]
    fn a_model_or_effort_on_the_command_applies_to_whichever_harness_is_chosen() {
        for (asked, model, effort) in [
            (set("sonnet", ""), "sonnet", "max"),
            (set("", "low"), "gpt-6.1-sol", "low"),
            (set("sonnet", "low"), "sonnet", "low"),
        ] {
            let asked = Asked {
                harness: None,
                model_and_effort: asked,
            };

            let chosen = Choice::of(&asked, &codex_default());

            assert_eq!(
                chosen,
                choice(Harness::Codex, model, effort, ChosenBy::UserConfig),
                "{asked:?}"
            );
        }
    }

    #[test]
    fn a_harness_with_nothing_set_leaves_its_model_and_effort_to_it() {
        let settings = Settings {
            default: Some(Harness::Claude),
            ..codex_default()
        };
        let asked = Asked {
            harness: Some(Harness::Codex),
            ..Asked::default()
        };
        let chosen = Choice::of(
            &asked,
            &Settings {
                codex: ModelAndEffort::default(),
                ..settings
            },
        );

        assert_eq!(chosen, choice(Harness::Codex, "", "", ChosenBy::Command));
    }

    #[test]
    fn claude_is_given_the_model_and_effort_that_are_set() {
        for (model, effort, args) in [
            ("opus", "", vec!["--model", "opus"]),
            ("", "max", vec!["--effort", "max"]),
            (
                "claude-opus-5-5",
                "high",
                vec!["--model", "claude-opus-5-5", "--effort", "high"],
            ),
        ] {
            let chosen = choice(Harness::Claude, model, effort, ChosenBy::Command);

            assert_eq!(chosen.claude_args(), args);
        }
    }

    #[test]
    fn the_built_with_line_names_the_harness_model_and_effort_or_the_harnesss_default() {
        for (chosen, line) in [
            (
                choice(
                    Harness::Claude,
                    "claude-opus-5-5",
                    "high",
                    ChosenBy::Command,
                ),
                "Built with claude · claude-opus-5-5 · high",
            ),
            (
                Choice::default(),
                "Built with claude · default model · default effort",
            ),
            (
                choice(Harness::Codex, "", "max", ChosenBy::UserConfig),
                "Built with codex · default model · max",
            ),
        ] {
            assert_eq!(chosen.built_with(), line);
        }
    }

    #[test]
    fn codex_is_given_the_model_and_the_effort_in_its_config() {
        for (model, effort, args) in [
            ("", "", vec![]),
            ("gpt-6.1-sol", "", vec!["-m", "gpt-6.1-sol"]),
            (
                "gpt-6.1-sol",
                "max",
                vec!["-m", "gpt-6.1-sol", "-c", "model_reasoning_effort=\"max\""],
            ),
        ] {
            let chosen = choice(Harness::Codex, model, effort, ChosenBy::Command);

            assert_eq!(chosen.codex_args(), args);
        }
    }

    /// A catalog as `codex debug models` prints one, trimmed to what is read.
    fn catalog() -> Catalog {
        Catalog::parse(
            r#"{"models": [
                {"slug": "gpt-6.1-sol", "display_name": "GPT-6.1-Sol", "visibility": "list",
                 "supported_reasoning_levels": [{"effort": "low"}, {"effort": "high"}, {"effort": "max"}]},
                {"slug": "gpt-5.5", "display_name": "GPT-5.5 Classic", "visibility": "list",
                 "supported_reasoning_levels": [{"effort": "low"}, {"effort": "xhigh"}]},
                {"slug": "codex-auto-review", "display_name": "Auto review", "visibility": "hide",
                 "supported_reasoning_levels": [{"effort": "minimal"}]}
            ]}"#,
        )
        .unwrap()
    }

    fn settled(model: Option<&str>, effort: Option<&str>) -> Result<ModelAndEffort> {
        catalog().settle(model, effort)
    }

    #[test]
    fn a_codex_model_and_effort_match_regardless_of_case_and_become_codexs_names() {
        for (model, effort, settled_as) in [
            (Some("GPT-6.1-Sol"), Some("Max"), set("gpt-6.1-sol", "max")),
            (Some("gpt-6.1-sol"), None, set("gpt-6.1-sol", "")),
            (
                Some("gpt-5.5 classic"),
                Some("XHIGH"),
                set("gpt-5.5", "xhigh"),
            ),
            (
                Some("codex-auto-review"),
                None,
                set("codex-auto-review", ""),
            ),
            (None, Some("High"), set("", "high")),
            (None, None, set("", "")),
        ] {
            assert_eq!(
                settled(model, effort).unwrap(),
                settled_as,
                "{model:?} {effort:?}"
            );
        }
    }

    #[test]
    fn an_unknown_codex_model_fails_naming_the_listed_models() {
        let error = settled(Some("gpt-7"), Some("max")).unwrap_err();

        assert_eq!(
            error.to_string(),
            "the Model gpt-7 is not in Codex's catalog: choose one of gpt-6.1-sol, gpt-5.5"
        );
    }

    #[test]
    fn an_effort_the_codex_model_does_not_support_fails_naming_those_it_does() {
        let error = settled(Some("GPT-5.5"), Some("max")).unwrap_err();

        assert_eq!(
            error.to_string(),
            "the Effort max is not one the Codex Model gpt-5.5 supports: choose one of low, xhigh"
        );
    }

    #[test]
    fn with_no_codex_model_the_effort_must_be_one_some_model_supports() {
        let error = settled(None, Some("ultra")).unwrap_err();

        assert_eq!(
            error.to_string(),
            "the Effort ultra is not one any Codex Model supports: choose one of low, high, max, \
             xhigh, minimal"
        );
    }

    #[test]
    fn the_catalog_lists_its_listed_models_by_slug_and_display_name() {
        assert_eq!(
            catalog().listed(),
            ["gpt-6.1-sol (GPT-6.1-Sol)", "gpt-5.5 (GPT-5.5 Classic)"]
        );
    }

    #[test]
    fn the_efforts_are_the_models_or_with_no_model_any_models_each_once() {
        let catalog = catalog();

        assert_eq!(catalog.efforts(Some("gpt-5.5")), ["low", "xhigh"]);
        assert_eq!(
            catalog.efforts(None),
            ["low", "high", "max", "xhigh", "minimal"]
        );
    }

    #[test]
    fn output_that_is_no_catalog_fails() {
        for output in ["", "not json", r#"{"models": 3}"#] {
            assert!(Catalog::parse(output).is_err(), "{output}");
        }
    }
}