thirdshift 0.35.1

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
//! Per-Step routing across the User config's routes by machine-local Plan
//! usage: before a session Step starts, its first route that is installed,
//! out of cooldown and below its utilization ceiling; and, when a session
//! stops on structured Plan-usage evidence, the next route not yet tried in
//! that Step. Routing reads only this machine's snapshot and its own
//! non-billed reads, never a Fleet peer.

use std::collections::BTreeMap;

use chrono::{DateTime, TimeDelta, Utc};

use super::route::{Route, Routing};
use super::store::{State, Store};
use super::view::Availability;
use crate::harness::{Asked, Choice, ChosenBy, Harness, Settings};

/// How old a snapshot of a Harness whose read reports Plan windows may grow
/// before routing refreshes it with that read.
const FRESH_MINUTES: i64 = 5;

/// One route a session Step may take: the configured entry, for its
/// ceiling and credits, and what a session on it runs on.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Candidate {
    pub route: Route,
    pub choice: Choice,
}

impl Candidate {
    fn of(route: &Route, settings: &Settings, chosen_by: ChosenBy) -> Self {
        Self {
            route: route.clone(),
            choice: route.choice(settings, chosen_by),
        }
    }

    /// A choice made elsewhere, as a route of its own: a Harness named by
    /// `security.harness` or `harness.default`, with the Model and Effort
    /// its section sets.
    fn chosen(choice: &Choice) -> Self {
        Self {
            route: Route {
                model: choice.model.clone(),
                effort: choice.effort.clone(),
                ..Route::named(choice.harness)
            },
            choice: choice.clone(),
        }
    }
}

/// The routes a Command's session Steps may take, in order: ordinary
/// sessions', and Security runs' and Security reviews'. With one route a
/// Step has nowhere to move, though its ceiling still holds it; with none
/// it is pinned.
#[derive(Debug, Clone, Default)]
pub struct Router {
    ordinary: Vec<Candidate>,
    security: Vec<Candidate>,
    routing: Routing,
}

/// A route picked for a Step, with why each earlier untried route was
/// passed over, as "claude is in cooldown".
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Picked {
    pub index: usize,
    pub passed: Vec<String>,
}

impl Router {
    /// No routing: every session runs on the choice it was given.
    pub fn pinned() -> Self {
        Self::default()
    }

    /// The routes for sessions on `harness`, and for Security sessions on
    /// `security_review`, else `harness`, given the User config's
    /// `settings` and `routing`. Only a choice the User config's routes made
    /// routes: a Harness or Model named by a command or a Step stays pinned.
    /// A Security session walks `security.routes` after `security.harness`,
    /// else `harness.routes`, else `security_default` (`harness.default`).
    pub fn of(
        settings: &Settings,
        routing: &Routing,
        harness: &Choice,
        security_review: Option<&Choice>,
        security_default: Option<&Choice>,
    ) -> Self {
        let routes: Vec<Candidate> = routing
            .routes
            .iter()
            .map(|route| Candidate::of(route, settings, ChosenBy::Routes))
            .collect();
        let ordinary = if harness.chosen_by == ChosenBy::Routes {
            routes.clone()
        } else {
            Vec::new()
        };
        let review = security_review.unwrap_or(harness);
        let default = security_default
            .cloned()
            .unwrap_or_else(|| Choice::of(&Asked::default(), settings));
        let mut security = Vec::new();
        match review.chosen_by {
            ChosenBy::SecurityConfig | ChosenBy::Routes => {
                if review.chosen_by == ChosenBy::SecurityConfig {
                    security.push(Candidate::chosen(review));
                }
                if !routing.security_routes.is_empty() {
                    security.extend(
                        routing
                            .security_routes
                            .iter()
                            .map(|route| Candidate::of(route, settings, ChosenBy::SecurityConfig)),
                    );
                } else if !routes.is_empty() {
                    security.extend(routes);
                } else {
                    security.push(Candidate::chosen(&default));
                }
            }
            // Pinned: a Security review keeps only its own fallback to
            // `harness.default` when it can't start.
            ChosenBy::Command | ChosenBy::UserConfig | ChosenBy::Default | ChosenBy::Step => {}
        }
        // A route that runs as an earlier one adds nothing to try.
        let mut distinct: Vec<Candidate> = Vec::new();
        for candidate in security {
            if !distinct
                .iter()
                .any(|kept| kept.choice.runs_as(&candidate.choice))
            {
                distinct.push(candidate);
            }
        }
        Self {
            ordinary,
            security: distinct,
            routing: routing.clone(),
        }
    }

    /// The routes sessions of this kind walk, in order: Security sessions'
    /// when `security`.
    pub fn candidates(&self, security: bool) -> &[Candidate] {
        if security {
            &self.security
        } else {
            &self.ordinary
        }
    }

    /// Every Harness a route names, so their Factory skills can be linked
    /// before a Step switches to one.
    pub fn harnesses(&self) -> Vec<Harness> {
        let mut all: Vec<Harness> = Vec::new();
        for candidate in self.ordinary.iter().chain(&self.security) {
            if !all.contains(&candidate.choice.harness) {
                all.push(candidate.choice.harness);
            }
        }
        all
    }

    /// The first route of this kind not in `tried` that could take a
    /// session now, by this machine's saved Plan usage, refreshing a stale
    /// snapshot with the Harness's non-billed read first. None when
    /// every untried route is unavailable, or there are fewer than two.
    pub fn pick(&self, security: bool, tried: &[usize]) -> Option<Picked> {
        let candidates = self.candidates(security);
        if candidates.len() < 2 {
            return None;
        }
        let saved = if cfg!(test) {
            BTreeMap::new()
        } else {
            let harnesses: Vec<Harness> = candidates
                .iter()
                .enumerate()
                .filter(|(index, _)| !tried.contains(index))
                .map(|(_, candidate)| candidate.choice.harness)
                .collect();
            Store::machine()
                .and_then(|store| {
                    super::refresh_for_routing(&store, &harnesses)?;
                    store.read()
                })
                .unwrap_or_default()
        };
        select(
            candidates,
            tried,
            &self.routing,
            &saved,
            Harness::installed,
            Utc::now(),
        )
    }
}

impl Router {
    /// The routes of this kind a session may take, in order, a lone
    /// configured route with its own ceiling and credits; else the one
    /// Harness it runs on, or `current`, as a pinned route held only at
    /// confirmed exhaustion.
    pub fn allowed(&self, security: bool, current: Harness) -> Vec<Route> {
        let candidates = self.candidates(security);
        let configured = |route: &Route| {
            self.routing.routes.contains(route) || self.routing.security_routes.contains(route)
        };
        if candidates.len() >= 2
            || candidates
                .iter()
                .any(|candidate| configured(&candidate.route))
        {
            return candidates
                .iter()
                .map(|candidate| candidate.route.clone())
                .collect();
        }
        let pinned = candidates
            .first()
            .map_or(current, |candidate| candidate.choice.harness);
        vec![super::exhaustion::pinned(pinned)]
    }

    /// Whether every route of this kind is unavailable by this machine's
    /// saved Plan usage, as a Step finds it before starting: the routes
    /// [`Router::allowed`] gives for `current`. None in unit tests, which
    /// read no snapshot.
    pub fn exhaustion(&self, security: bool, current: Harness) -> Option<super::Exhaustion> {
        if cfg!(test) {
            return None;
        }
        let saved = Store::machine().and_then(|store| store.read()).ok()?;
        super::exhaustion::judge(
            &self.allowed(security, current),
            &self.routing,
            &saved,
            Harness::installed,
            Utc::now(),
        )
    }
}

/// The first of `candidates` not in `tried` whose route could take a
/// session now, by the `saved` Plan usage and which Harnesses are
/// `installed`. A route Plan usage does not watch is usable when installed.
fn select(
    candidates: &[Candidate],
    tried: &[usize],
    routing: &Routing,
    saved: &BTreeMap<String, State>,
    installed: impl Fn(Harness) -> bool,
    now: DateTime<Utc>,
) -> Option<Picked> {
    let mut passed = Vec::new();
    for (index, candidate) in candidates.iter().enumerate() {
        if tried.contains(&index) {
            continue;
        }
        let harness = candidate.choice.harness;
        let installed = installed(harness);
        let availability = if super::observation::subscription(harness) {
            saved
                .get(harness.name())
                .cloned()
                .unwrap_or_default()
                .availability(&candidate.route, routing, installed, now)
        } else if installed {
            Availability::Available
        } else {
            Availability::NotInstalled
        };
        if availability.usable() {
            return Some(Picked { index, passed });
        }
        passed.push(format!("{} is {availability}", harness.name()));
    }
    None
}

/// Whether routing should refresh `state` with a non-billed read before
/// judging it: nothing saved, the last observation more than
/// [`FRESH_MINUTES`] old, or a window or cooldown past its reset.
pub(super) fn stale(state: Option<&State>, now: DateTime<Utc>) -> bool {
    let Some(state) = state else {
        return true;
    };
    state.observed_at.is_none_or(|observed| {
        observed > now || now - observed >= TimeDelta::minutes(FRESH_MINUTES)
    }) || state.windows.iter().any(|window| window.reset_by(now))
        || state
            .cooldown
            .as_ref()
            .is_some_and(|cooldown| cooldown.until <= now)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plan_usage::observation::{Exhausted, Observation, Window};
    use crate::plan_usage::store::Cooldown;

    fn routes(routes: &[Route]) -> Routing {
        Routing {
            routes: routes.to_vec(),
            ..Routing::default()
        }
    }

    fn routed(harness: Harness) -> Choice {
        Choice {
            harness,
            model: None,
            effort: None,
            chosen_by: ChosenBy::Routes,
        }
    }

    fn harnesses(candidates: &[Candidate]) -> Vec<Harness> {
        candidates.iter().map(|c| c.choice.harness).collect()
    }

    fn window(used: f64, resets_at: DateTime<Utc>) -> State {
        State {
            observed_at: Some(Utc::now()),
            windows: vec![Window {
                used_percent: Some(used),
                resets_at: Some(resets_at),
                ..Window::named("five_hour").unwrap()
            }],
            ..State::default()
        }
    }

    fn picked(
        router: &Router,
        security: bool,
        tried: &[usize],
        saved: &BTreeMap<String, State>,
        now: DateTime<Utc>,
    ) -> Option<usize> {
        select(
            router.candidates(security),
            tried,
            &router.routing,
            saved,
            |_| true,
            now,
        )
        .map(|picked| picked.index)
    }

    #[test]
    fn only_a_choice_the_routes_made_routes_ordinary_sessions() {
        let routing = routes(&[Route::named(Harness::Claude), Route::named(Harness::Codex)]);
        let settings = Settings::default();
        let router = Router::of(&settings, &routing, &routed(Harness::Claude), None, None);
        assert_eq!(
            harnesses(router.candidates(false)),
            [Harness::Claude, Harness::Codex]
        );
        for chosen_by in [
            ChosenBy::Command,
            ChosenBy::Step,
            ChosenBy::UserConfig,
            ChosenBy::Default,
        ] {
            let pinned = Choice {
                chosen_by,
                ..routed(Harness::Claude)
            };
            let router = Router::of(&settings, &routing, &pinned, None, None);
            assert!(router.candidates(false).is_empty(), "{chosen_by:?}");
            assert_eq!(router.pick(false, &[]), None, "{chosen_by:?}");
        }
    }

    #[test]
    fn a_reserve_ceiling_or_cooldown_routes_away_and_a_lapsed_cooldown_revalidates() {
        let now = Utc::now();
        let routing = Routing {
            max_utilization: 85,
            ..routes(&[Route::named(Harness::Claude), Route::named(Harness::Codex)])
        };
        let router = Router::of(
            &Settings::default(),
            &routing,
            &routed(Harness::Claude),
            None,
            None,
        );
        let mut saved = BTreeMap::new();
        assert_eq!(picked(&router, false, &[], &saved, now), Some(0));
        saved.insert("claude".into(), window(90.0, now + TimeDelta::hours(1)));
        assert_eq!(picked(&router, false, &[], &saved, now), Some(1));
        // The window reset since: its utilization says nothing now.
        saved.insert("claude".into(), window(90.0, now - TimeDelta::minutes(1)));
        assert_eq!(picked(&router, false, &[], &saved, now), Some(0));
        let mut cooled = State::default();
        cooled.observe(
            &Observation {
                harness: Harness::Claude,
                windows: Vec::new(),
                exhausted: Some(Exhausted::default()),
            },
            "session",
            now,
        );
        saved.insert("claude".into(), cooled.clone());
        assert_eq!(picked(&router, false, &[], &saved, now), Some(1));
        // Each route is tried at most once in a Step.
        assert_eq!(picked(&router, false, &[1], &saved, now), None);
        // Past the backoff the next Step may try it once again.
        let later = cooled.cooldown.as_ref().unwrap().until + TimeDelta::minutes(1);
        assert_eq!(picked(&router, false, &[], &saved, later), Some(0));
    }

    #[test]
    fn credits_hold_a_used_up_window_unless_the_route_allows_them() {
        let now = Utc::now();
        let mut codex = window(100.0, now + TimeDelta::days(3));
        codex.credits = Some(crate::plan_usage::store::Credits {
            has_credits: Some(true),
            balance: Some("100".into()),
        });
        let saved = BTreeMap::from([("codex".to_string(), codex)]);
        for (allow_credits, expected) in [(false, Some(1)), (true, Some(0))] {
            let routing = routes(&[
                Route {
                    allow_credits,
                    ..Route::named(Harness::Codex)
                },
                Route::named(Harness::Claude),
            ]);
            let router = Router::of(
                &Settings::default(),
                &routing,
                &routed(Harness::Codex),
                None,
                None,
            );
            assert_eq!(
                picked(&router, false, &[], &saved, now),
                expected,
                "{allow_credits}"
            );
        }
    }

    #[test]
    fn security_sessions_walk_security_routes_else_harness_routes_else_the_default() {
        let settings = Settings {
            default: Some(Harness::Claude),
            ..Settings::default()
        };
        let security = Choice {
            chosen_by: ChosenBy::SecurityConfig,
            ..routed(Harness::Codex)
        };
        let default = Choice {
            chosen_by: ChosenBy::UserConfig,
            ..routed(Harness::Claude)
        };
        let with_security_routes = Routing {
            security_routes: vec![Route::named(Harness::Muse), Route::named(Harness::Agy)],
            ..routes(&[Route::named(Harness::Claude), Route::named(Harness::Grok)])
        };
        let only_routes = routes(&[Route::named(Harness::Claude), Route::named(Harness::Grok)]);
        for (routing, expected) in [
            (
                &with_security_routes,
                vec![Harness::Codex, Harness::Muse, Harness::Agy],
            ),
            (
                &only_routes,
                vec![Harness::Codex, Harness::Claude, Harness::Grok],
            ),
            (&Routing::default(), vec![Harness::Codex, Harness::Claude]),
        ] {
            let router = Router::of(
                &settings,
                routing,
                &routed(Harness::Claude),
                Some(&security),
                Some(&default),
            );
            assert_eq!(harnesses(router.candidates(true)), expected);
        }
        // A pinned Command's Security sessions don't route; a Security
        // review keeps its own fallback to the default.
        let pinned = Choice {
            chosen_by: ChosenBy::Command,
            ..routed(Harness::Grok)
        };
        let router = Router::of(&settings, &only_routes, &pinned, None, Some(&default));
        assert!(router.candidates(true).is_empty());
        assert!(router.candidates(false).is_empty());
    }

    #[test]
    fn old_or_reset_snapshots_are_stale_for_routing() {
        let now = Utc::now();
        assert!(stale(None, now));
        let fresh = State {
            observed_at: Some(now),
            ..window(10.0, now + TimeDelta::hours(1))
        };
        assert!(!stale(Some(&fresh), now));
        let old = State {
            observed_at: Some(now - TimeDelta::minutes(6)),
            ..fresh.clone()
        };
        assert!(stale(Some(&old), now));
        let reset = window(10.0, now - TimeDelta::seconds(1));
        assert!(stale(Some(&reset), now));
        let lapsed = State {
            cooldown: Some(Cooldown {
                since: now - TimeDelta::hours(2),
                until: now - TimeDelta::hours(1),
                window: None,
                overage: None,
                backoff_minutes: Some(60),
            }),
            ..fresh.clone()
        };
        assert!(stale(Some(&lapsed), now));
    }
}