basis 0.12.2

The basis SDK: workspace discovery, run lifecycle, one event stream, and the two seams. No protocol, no transport, no TTY.
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
//! What one turn may spend, and how it can be stopped.
//!
//! A sibling of [`RunSpec`](crate::RunSpec) rather than something owned by
//! the run: the spec says what a *run* may spend, this says what one call
//! may, and [`bounded`] is the only place that distinction is resolved.

use std::sync::Arc;
use std::time::{Duration, SystemTime};

use mentra::RoundStrategy;
use mentra::runtime::{CancellationToken, ProviderRetry, RunOptions};

use super::{Bounds, RunError};
use crate::{budget::BudgetPool, runtime::RetryPolicy};

/// Limits and stop signals for a single turn.
///
/// basis's own type rather than a re-export of mentra's `RunOptions`: the same
/// reasoning as [`Event`](crate::Event) — basis owns its surface so mentra's
/// internals can move without breaking basis's callers. Only the knobs a harness
/// actually needs are exposed; the rest stay at mentra's defaults.
#[derive(Clone, Default)]
pub struct TurnOptions {
    /// Trips to abandon the turn. The turn fails and is rolled back — what a
    /// client's stop button means.
    pub cancel: Option<CancellationToken>,
    /// Trips to end the turn gracefully at the next round boundary, keeping
    /// what the model has already committed.
    ///
    /// One caveat, upstream and honest: mentra ends the turn but still owes its
    /// caller a final assistant message, so a stop that lands after a *tool*
    /// round — where the last committed message is the tool's result — comes
    /// back as a failed turn even though nothing was rolled back. The work is
    /// kept either way; the report is what disagrees. `basis`'s
    /// `tests/cancellation.rs` pins that behavior so a change to it is noticed.
    ///
    /// A stopped turn reports no [`Bound`](crate::Bound), unlike a spent
    /// [`Bounds::token_budget`]. A bound is an allowance the
    /// run outgrew, and a script is right to retry one with a bigger number; a
    /// stop is an instruction whoever holds this token issued, and retrying it
    /// would undo their decision.
    pub stop: Option<CancellationToken>,
    /// What this one call may spend — deadline, tool budget, token budget.
    ///
    /// One caveat here beyond what [`Bounds`] itself says, and it matters: a
    /// token budget ends the turn *gracefully*, and the caveat on
    /// [`stop`](Self::stop) about how a graceful end is reported applies — a
    /// turn stopped after a tool round comes back failed for want of a final
    /// message, and without the named bound that failure is indistinguishable
    /// from a provider's. `basis`'s `tests/token_budget.rs` drives exactly
    /// that shape.
    pub bounds: Bounds,
    /// An exact wall-clock deadline for this turn.
    ///
    /// The absolute sibling of [`Bounds::deadline`]. Builder calls treat the
    /// two as one last-writer-wins dimension; if a direct struct literal sets
    /// both, the absolute value wins when the Mentra options are built.
    pub absolute_deadline: Option<SystemTime>,
    /// Maximum main-model requests this turn may issue, including retries.
    ///
    /// `Some(0)` is meaningful: refuse before the first provider request.
    pub model_budget: Option<usize>,
    /// Per-turn override for the runtime's provider retry schedule.
    pub provider_retry: Option<ProviderRetry>,
    /// Per-turn override for the runtime's retry count after the initial call.
    ///
    /// `Some(0)` disables retries. The schedule and count override
    /// independently so changing one retains the runtime fallback for the
    /// other.
    pub retry_budget: Option<usize>,
    /// An allowance this turn shares with every other run drawing on it.
    ///
    /// The other kind of token bound, and the two compose rather than compete:
    /// [`Bounds::token_budget`] says what *this* turn may spend, a
    /// pool says what the whole job may, and a turn carrying both stops at
    /// whichever comes first. See [`BudgetPool`] for how that is arranged, and
    /// for the overshoot a shared soft bound implies.
    ///
    /// A turn drawing on a pool with nothing left is refused before its prompt
    /// is sent, with [`RunError::BudgetExhausted`](crate::RunError::BudgetExhausted).
    pub budget: Option<BudgetPool>,
    /// A policy consulted at each round boundary of this one call — after a
    /// committed tool round, and after a committed tool-free assistant message
    /// before the turn returns it.
    ///
    /// The steering surface: at either boundary the strategy may proceed,
    /// inject a corrective user turn and run another round, switch the model
    /// or reasoning for the rounds that follow
    /// ([`RoundAdjustment`](crate::RoundAdjustment)), or end the turn
    /// gracefully. `None` — the default — reproduces the round loop exactly as
    /// it runs without one; a strategy that always proceeds is inert.
    ///
    /// Per call, like the two tokens above and unlike
    /// [`bounds`](Self::bounds): mentra binds a strategy to exactly one run so
    /// its state cannot leak into another, and a configured fallback here
    /// would quietly share one strategy's state across every turn of a
    /// conversation. A caller that wants the same policy each turn attaches it
    /// each turn.
    ///
    /// Every decision still passes the run's bounds: an injected round is a
    /// normal round, refused like any other once a budget is spent or a
    /// deadline passed. A strategy's *stop* is the reverse — an instruction,
    /// not an allowance — so a turn it ends reports no
    /// [`Bound`](crate::Bound), exactly as [`stop`](Self::stop) does, and the
    /// caveat there about a stop that lands after a tool round applies to a
    /// strategy's stop unchanged. `basis`'s `tests/round_strategy.rs` pins
    /// both facts.
    ///
    /// `Arc` because that is how mentra carries it — the strategy is shared
    /// with the runner, not copied — and a host usually holds its half to read
    /// what the strategy observed after the turn.
    pub round_strategy: Option<Arc<dyn RoundStrategy>>,
}

/// By hand because a strategy is opaque: presence is the only honest thing a
/// debug line can say about a `dyn` policy, and deriving would instead forbid
/// `Debug` on every struct that embeds these options.
impl std::fmt::Debug for TurnOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TurnOptions")
            .field("cancel", &self.cancel)
            .field("stop", &self.stop)
            .field("bounds", &self.bounds)
            .field("absolute_deadline", &self.absolute_deadline)
            .field("model_budget", &self.model_budget)
            .field("provider_retry", &self.provider_retry)
            .field("retry_budget", &self.retry_budget)
            .field("budget", &self.budget)
            .field(
                "round_strategy",
                &self.round_strategy.as_ref().map(|_| ".."),
            )
            .finish()
    }
}

impl TurnOptions {
    /// A turn that can be abandoned through the returned token.
    ///
    /// What a client's stop button trips: the turn fails with
    /// [`RunOutcome::Error`](crate::RunOutcome::Error) and mentra rolls it back, so the session is left
    /// as it was before the prompt. For "stop when you have enough, and keep
    /// it", see [`stoppable`](Self::stoppable).
    pub fn cancellable() -> (Self, CancellationToken) {
        let token = CancellationToken::default();
        (
            Self {
                cancel: Some(token.clone()),
                ..Self::default()
            },
            token,
        )
    }

    /// A turn that can be ended gracefully through the returned token.
    ///
    /// The other half of the pair, and the difference is what happens to the
    /// work: this one lets the round in flight finish and keeps everything the
    /// model committed, where [`cancellable`](Self::cancellable) throws the
    /// turn away. A caller watching the stream and deciding it has read enough
    /// wants this one; a caller whose user pressed stop wants the other. Mind
    /// the caveat on [`stop`](Self::stop) about how the kept work is reported.
    pub fn stoppable() -> (Self, CancellationToken) {
        let token = CancellationToken::default();
        (
            Self {
                stop: Some(token.clone()),
                ..Self::default()
            },
            token,
        )
    }

    /// Attaches a token that abandons the turn — for a caller that already
    /// holds one, because it arms the token before it knows which turn it will
    /// stop.
    pub fn with_cancel(self, cancel: CancellationToken) -> Self {
        Self {
            cancel: Some(cancel),
            ..self
        }
    }

    /// Attaches a token that ends the turn gracefully at the next round
    /// boundary.
    pub fn with_stop(self, stop: CancellationToken) -> Self {
        Self {
            stop: Some(stop),
            ..self
        }
    }

    /// Gives up on the turn after `deadline`. Sugar into
    /// [`bounds`](Self::bounds).
    pub fn with_deadline(self, deadline: Duration) -> Self {
        Self {
            bounds: self.bounds.with_deadline(deadline),
            absolute_deadline: None,
            ..self
        }
    }

    /// Gives up at the exact wall-clock `deadline`.
    ///
    /// Clears a relative deadline already present; a later
    /// [`with_deadline`](Self::with_deadline) clears this in turn.
    pub fn with_absolute_deadline(self, deadline: SystemTime) -> Self {
        Self {
            bounds: Bounds {
                deadline: None,
                ..self.bounds
            },
            absolute_deadline: Some(deadline),
            ..self
        }
    }

    /// Caps how many main-model requests this turn may issue.
    pub fn with_model_budget(self, model_budget: usize) -> Self {
        Self {
            model_budget: Some(model_budget),
            ..self
        }
    }

    /// Overrides the runtime's provider retry schedule for this turn.
    pub fn with_provider_retry(self, provider_retry: ProviderRetry) -> Self {
        Self {
            provider_retry: Some(provider_retry),
            ..self
        }
    }

    /// Overrides how many retries this turn gets after its initial call.
    pub fn with_retry_budget(self, retry_budget: usize) -> Self {
        Self {
            retry_budget: Some(retry_budget),
            ..self
        }
    }

    /// Caps how many tool calls this turn may make. Sugar into
    /// [`bounds`](Self::bounds).
    pub fn with_tool_budget(self, tool_budget: usize) -> Self {
        Self {
            bounds: self.bounds.with_tool_budget(tool_budget),
            ..self
        }
    }

    /// Caps the tokens this turn may report using. Sugar into
    /// [`bounds`](Self::bounds).
    pub fn with_token_budget(self, token_budget: u64) -> Self {
        Self {
            bounds: self.bounds.with_token_budget(token_budget),
            ..self
        }
    }

    /// Draws this turn's tokens from an allowance shared with other runs.
    ///
    /// Immutable like the rest — a new value, the same pool. That is the whole
    /// shape of the exception [`BudgetPool`] makes: options are copied, the
    /// allowance is shared.
    pub fn with_budget(self, budget: BudgetPool) -> Self {
        Self {
            budget: Some(budget),
            ..self
        }
    }

    /// Steers this one call through `strategy`, consulted at each round
    /// boundary. See [`round_strategy`](Self::round_strategy) for what a
    /// strategy may decide and what it can never override.
    pub fn with_round_strategy(self, strategy: Arc<dyn RoundStrategy>) -> Self {
        Self {
            round_strategy: Some(strategy),
            ..self
        }
    }

    /// Builds Mentra's controls around the runtime's retry fallback.
    ///
    /// A turn-level schedule or count overrides its corresponding half
    /// independently; omission retains the runtime's answer.
    pub(super) fn into_run_options(self, retry: RetryPolicy) -> RunOptions {
        let options = RunOptions {
            cancellation: self.cancel,
            stop: self.stop,
            deadline: self
                .absolute_deadline
                .or_else(|| self.bounds.deadline.map(|after| SystemTime::now() + after)),
            tool_budget: self.bounds.tool_budget,
            model_budget: self.model_budget,
            token_budget: self.bounds.token_budget,
            round_strategy: self.round_strategy,
            provider_retry: self.provider_retry.unwrap_or(retry.schedule),
            retry_budget: self.retry_budget.unwrap_or(retry.budget),
            ..RunOptions::default()
        };

        // Installing the pool's counter is what makes the bound shared: mentra
        // adds each round's usage to whatever handle it was given and checks
        // the bound against that total, so every run on one pool is measured
        // against every other's spending rather than its own.
        match self.budget {
            Some(pool) => RunOptions {
                token_budget: Some(pool.turn_bound(self.bounds.token_budget)),
                token_usage: pool.counter(),
                ..options
            },
            None => options,
        }
    }
}
/// Fills in whatever `options` left unset from the run's configured bounds.
///
/// A caller that passes options in order to attach a cancellation token has
/// said nothing about limits, and reading that silence as "no deadline" would
/// unbound a run whose config asked for one.
pub(super) fn bounded(options: TurnOptions, configured: &TurnOptions) -> TurnOptions {
    // Cloned rather than moved out, because taking the field would leave
    // `options` partially moved and the `..options` below could not finish the
    // job. It is an `Arc` either way.
    let budget = options.budget.clone().or_else(|| configured.budget.clone());
    let explicit_deadline =
        options.absolute_deadline.is_some() || options.bounds.deadline.is_some();
    let mut bounds = options.bounds.or(configured.bounds);
    let absolute_deadline = if explicit_deadline {
        options.absolute_deadline
    } else {
        configured.absolute_deadline
    };
    if absolute_deadline.is_some() {
        bounds.deadline = None;
    }

    TurnOptions {
        bounds,
        absolute_deadline,
        model_budget: options.model_budget.or(configured.model_budget),
        provider_retry: options.provider_retry.or(configured.provider_retry),
        retry_budget: options.retry_budget.or(configured.retry_budget),
        budget,
        ..options
    }
}

/// Refuses a turn whose shared allowance is already spent.
///
/// Checked here — before a header is emitted, before a prompt is sent, before
/// anything is committed — rather than left to mentra, which would take the
/// turn, run no rounds, and report the missing assistant message as a provider
/// error. See [`BudgetPool`] for the whole argument.
pub(super) fn drawable(options: &TurnOptions) -> Result<(), RunError> {
    let Some(pool) = &options.budget else {
        return Ok(());
    };

    if pool.is_exhausted() {
        return Err(RunError::BudgetExhausted {
            limit: pool.limit(),
            spent: pool.spent(),
        });
    }

    Ok(())
}
#[cfg(test)]
mod tests {
    use super::*;
    use crate::run::RunUsage;

    /// Builds the mentra options for a turn whose provider connection is
    /// nobody's business here: every test below is about a *bound*, and the
    /// retry schedule beside it is the runtime's
    /// ([`RuntimeBuilder::with_provider_retry`](crate::RuntimeBuilder::with_provider_retry)),
    /// asserted where it is set rather than restated in each of these.
    fn as_mentra_would(options: TurnOptions) -> RunOptions {
        options.into_run_options(RetryPolicy::default())
    }

    #[test]
    fn attaching_a_token_does_not_unbound_a_configured_run() {
        // What ACP does on every turn: options exist only to carry a stop
        // button. Reading that as "and no deadline either" would silently
        // remove the bound an unattended caller asked for.
        let configured = TurnOptions::default()
            .with_deadline(Duration::from_secs(600))
            .with_tool_budget(12);
        let (options, token) = TurnOptions::cancellable();

        let merged = bounded(options, &configured);

        assert_eq!(merged.bounds.deadline, Some(Duration::from_secs(600)));
        assert_eq!(merged.bounds.tool_budget, Some(12));
        assert!(merged.cancel.is_some(), "the token still arrives");
        assert!(!token.is_cancelled());
    }

    #[test]
    fn stopping_and_cancelling_are_different_signals() {
        // They end a turn differently — one keeps the committed work and
        // reports success, the other throws it away and reports failure — so a
        // turn must never receive one where the caller asked for the other.
        let (cancellable, cancel) = TurnOptions::cancellable();
        let (stoppable, stop) = TurnOptions::stoppable();

        assert!(cancellable.cancel.is_some() && cancellable.stop.is_none());
        assert!(stoppable.stop.is_some() && stoppable.cancel.is_none());

        cancel.cancel();
        assert!(
            !stop.is_cancelled(),
            "one turn's stop button is not another's"
        );
    }

    #[test]
    fn a_turn_can_carry_both_signals_at_once() {
        // A harness offering both "stop when you have enough" and "abandon
        // this" arms both, so attaching one must not clear the other.
        let (options, cancel) = TurnOptions::cancellable();
        let stop = CancellationToken::default();

        let both = options.with_stop(stop.clone());

        assert!(
            both.cancel.is_some(),
            "the first signal survives the second"
        );
        assert!(both.stop.is_some());
        assert!(!cancel.is_cancelled() && !stop.is_cancelled());
    }

    #[test]
    fn attaching_a_token_returns_a_new_value() {
        let base = TurnOptions::default();
        let armed = base.clone().with_cancel(CancellationToken::default());

        assert!(base.cancel.is_none(), "the original must be untouched");
        assert!(armed.cancel.is_some());
    }

    #[test]
    fn an_explicit_bound_wins_over_the_configured_one() {
        let configured = TurnOptions::default().with_deadline(Duration::from_secs(600));
        let explicit = TurnOptions::default().with_deadline(Duration::from_secs(30));

        assert_eq!(
            bounded(explicit, &configured).bounds.deadline,
            Some(Duration::from_secs(30))
        );
    }

    #[test]
    fn an_absolute_deadline_reaches_mentra_byte_for_byte() {
        let deadline = SystemTime::UNIX_EPOCH + Duration::from_secs(1_900_000_000);
        let options = TurnOptions {
            // A direct conflicting literal still resolves deterministically.
            bounds: Bounds::default().with_deadline(Duration::from_secs(1)),
            absolute_deadline: Some(deadline),
            ..TurnOptions::default()
        };

        assert_eq!(as_mentra_would(options).deadline, Some(deadline));
    }

    #[test]
    fn relative_and_absolute_deadline_builders_are_last_call_wins() {
        let absolute = SystemTime::UNIX_EPOCH + Duration::from_secs(1_900_000_000);
        let absolute_last = TurnOptions::default()
            .with_deadline(Duration::from_secs(60))
            .with_absolute_deadline(absolute);
        assert_eq!(absolute_last.absolute_deadline, Some(absolute));
        assert_eq!(absolute_last.bounds.deadline, None);

        let relative_last = TurnOptions::default()
            .with_absolute_deadline(absolute)
            .with_deadline(Duration::from_secs(30));
        assert_eq!(relative_last.absolute_deadline, None);
        assert_eq!(relative_last.bounds.deadline, Some(Duration::from_secs(30)));
    }

    #[test]
    fn model_and_retry_controls_map_exactly_and_inherit_by_half() {
        let runtime_policy = RetryPolicy {
            schedule: ProviderRetry {
                base_delay: Duration::from_secs(7),
                max_delay: Duration::from_secs(11),
                retry_after_cap: Duration::from_secs(13),
            },
            budget: 17,
        };
        let turn_retry = ProviderRetry {
            base_delay: Duration::from_millis(1),
            max_delay: Duration::from_millis(2),
            retry_after_cap: Duration::from_millis(3),
        };

        let schedule_only = TurnOptions::default()
            .with_model_budget(0)
            .with_provider_retry(turn_retry)
            .into_run_options(runtime_policy);
        assert_eq!(schedule_only.model_budget, Some(0));
        assert_eq!(schedule_only.provider_retry, turn_retry);
        assert_eq!(schedule_only.retry_budget, 17);

        let count_only = TurnOptions::default()
            .with_retry_budget(0)
            .into_run_options(runtime_policy);
        assert_eq!(count_only.provider_retry, runtime_policy.schedule);
        assert_eq!(count_only.retry_budget, 0);
    }

    #[test]
    fn explicit_turn_controls_beat_configured_and_omissions_inherit() {
        let configured_deadline = SystemTime::UNIX_EPOCH + Duration::from_secs(1_900_000_000);
        let configured_retry = ProviderRetry {
            base_delay: Duration::from_secs(1),
            max_delay: Duration::from_secs(2),
            retry_after_cap: Duration::from_secs(3),
        };
        let configured = TurnOptions::default()
            .with_absolute_deadline(configured_deadline)
            .with_model_budget(8)
            .with_provider_retry(configured_retry)
            .with_retry_budget(9);

        let explicit = TurnOptions::default()
            .with_deadline(Duration::from_secs(5))
            .with_model_budget(2)
            .with_retry_budget(1);
        let merged = bounded(explicit, &configured);
        assert_eq!(merged.absolute_deadline, None);
        assert_eq!(merged.bounds.deadline, Some(Duration::from_secs(5)));
        assert_eq!(merged.model_budget, Some(2));
        assert_eq!(merged.provider_retry, Some(configured_retry));
        assert_eq!(merged.retry_budget, Some(1));

        let inherited = bounded(TurnOptions::default().with_token_budget(500), &configured);
        assert_eq!(inherited.absolute_deadline, Some(configured_deadline));
        assert_eq!(inherited.bounds.deadline, None);
        assert_eq!(inherited.model_budget, Some(8));
        assert_eq!(inherited.provider_retry, Some(configured_retry));
        assert_eq!(inherited.retry_budget, Some(9));
        assert_eq!(inherited.bounds.token_budget, Some(500));
    }

    #[test]
    fn a_prepared_run_is_unbounded_until_it_is_bounded() {
        let unset = TurnOptions::default();

        let merged = bounded(TurnOptions::default(), &unset);
        assert_eq!(merged.bounds, Bounds::default());
        assert!(bounded(TurnOptions::default(), &unset).budget.is_none());
    }

    #[test]
    fn a_pool_bounds_the_turn_at_the_whole_jobs_allowance() {
        // Not at the run's share of it: the counter is shared, so the figure
        // handed to mentra is the job's and every drawing run is measured
        // against every other's spending.
        let pool = BudgetPool::new(500_000);
        let options = TurnOptions::default().with_budget(pool.clone());

        assert_eq!(as_mentra_would(options).token_budget, Some(500_000));
    }

    #[test]
    fn a_pooled_turn_reports_into_the_pools_own_counter() {
        // The claim the whole design rests on. If mentra were handed a fresh
        // counter, each run would get the pool's limit to itself and the job
        // would cost N times what was asked for.
        let pool = BudgetPool::new(1_000);
        let run_options = as_mentra_would(TurnOptions::default().with_budget(pool.clone()));

        pool.record(RunUsage {
            input_tokens: 300,
            ..RunUsage::default()
        });

        assert_eq!(
            run_options.reported_tokens(),
            300,
            "mentra reads the spending the pool records, and the reverse"
        );
    }

    #[test]
    fn an_unpooled_turn_gets_a_counter_of_its_own() {
        // Two unpooled runs must not accidentally share accounting, which they
        // would if basis reused one handle instead of letting mentra's default
        // mint a fresh one per turn.
        let first = as_mentra_would(TurnOptions::default().with_token_budget(100));
        let second = as_mentra_would(TurnOptions::default().with_token_budget(100));

        assert!(!std::sync::Arc::ptr_eq(
            &first.token_usage,
            &second.token_usage
        ));
    }

    #[test]
    fn a_per_turn_cap_and_a_pool_both_bind() {
        // mentra has one bound per run, so the two have to be resolved into one
        // figure here. A cap of 50k on a pool that has spent 200k of 500k means
        // "stop at 250k of the job's total" — tighter than the pool, and the
        // pool is still the ceiling when the cap is the looser of the two.
        let pool = BudgetPool::new(500_000);
        pool.record(RunUsage {
            input_tokens: 200_000,
            ..RunUsage::default()
        });

        let capped = TurnOptions::default()
            .with_budget(pool.clone())
            .with_token_budget(50_000);
        assert_eq!(as_mentra_would(capped).token_budget, Some(250_000));

        let generous = TurnOptions::default()
            .with_budget(pool)
            .with_token_budget(u64::MAX);
        assert_eq!(as_mentra_would(generous).token_budget, Some(500_000));
    }

    #[test]
    fn attaching_a_token_does_not_detach_the_pool() {
        // The same argument as the deadline above, and the expensive version of
        // it: a stop button that quietly unbounded the shared allowance would
        // let a fan-out spend without limit.
        let pool = BudgetPool::new(1_000);
        let configured = TurnOptions::default().with_budget(pool.clone());
        let (options, _token) = TurnOptions::stoppable();

        assert_eq!(bounded(options, &configured).budget, Some(pool));
    }

    #[test]
    fn an_explicit_pool_wins_over_the_configured_one() {
        let configured = TurnOptions::default().with_budget(BudgetPool::new(1_000));
        let explicit = BudgetPool::new(50);

        let merged = bounded(
            TurnOptions::default().with_budget(explicit.clone()),
            &configured,
        );

        assert_eq!(merged.budget, Some(explicit));
    }

    #[test]
    fn a_turn_on_a_spent_pool_is_refused_rather_than_sent() {
        let pool = BudgetPool::new(100);
        let options = TurnOptions::default().with_budget(pool.clone());

        assert!(drawable(&options).is_ok(), "a full pool draws");

        pool.record(RunUsage {
            input_tokens: 120,
            ..RunUsage::default()
        });

        let refused = drawable(&options).expect_err("a spent pool refuses");
        assert!(matches!(
            refused,
            RunError::BudgetExhausted {
                limit: 100,
                spent: 120
            }
        ));
    }

    #[test]
    fn a_turn_with_no_pool_is_always_drawable() {
        assert!(drawable(&TurnOptions::default().with_token_budget(0)).is_ok());
    }

    /// A strategy that proceeds everywhere — enough to prove carriage, since
    /// what these tests assert is *which object* mentra receives, not what it
    /// decides.
    struct Quiet;

    #[async_trait::async_trait]
    impl RoundStrategy for Quiet {
        async fn on_round(&self, _ctx: mentra::RoundContext<'_>) -> mentra::RoundDecision {
            mentra::RoundDecision::proceed()
        }
    }

    #[test]
    fn the_strategy_a_caller_attached_is_the_one_mentra_receives() {
        // Identity, not equality: mentra shares the strategy with the runner
        // through the `Arc`, so a copy would be a second policy with its own
        // state and the caller's half would observe nothing.
        let strategy: Arc<dyn RoundStrategy> = Arc::new(Quiet);
        let options = TurnOptions::default().with_round_strategy(Arc::clone(&strategy));

        let run_options = as_mentra_would(options);

        let installed = run_options
            .round_strategy
            .expect("the strategy must reach mentra");
        assert!(Arc::ptr_eq(&installed, &strategy));
    }

    #[test]
    fn a_turn_without_a_strategy_hands_mentra_none() {
        // The default must reproduce today's round loop exactly: mentra's
        // `None` is the built-in loop, and anything else here would change
        // behavior for every caller that asked for nothing.
        assert!(
            as_mentra_would(TurnOptions::default())
                .round_strategy
                .is_none()
        );
    }

    #[test]
    fn a_strategy_rides_the_merge_and_the_configured_bounds_still_fill_in() {
        // The same claim `bounded` makes for the tokens: attaching a per-call
        // extra says nothing about limits, so the configured deadline must
        // still arrive — and the strategy must survive the merge that fills it.
        let configured = TurnOptions::default().with_deadline(Duration::from_secs(600));
        let options = TurnOptions::default().with_round_strategy(Arc::new(Quiet));

        let merged = bounded(options, &configured);

        assert!(
            merged.round_strategy.is_some(),
            "the strategy still arrives"
        );
        assert_eq!(merged.bounds.deadline, Some(Duration::from_secs(600)));
    }

    #[test]
    fn a_configured_strategy_is_not_adopted_by_a_plain_turn() {
        // Per call, like the tokens and unlike the bounds: mentra binds a
        // strategy's state to one run, so a configured fallback would share
        // one strategy across every turn of a conversation — exactly the leak
        // the upstream contract exists to prevent.
        let configured = TurnOptions::default().with_round_strategy(Arc::new(Quiet));

        let merged = bounded(TurnOptions::default(), &configured);

        assert!(merged.round_strategy.is_none());
    }

    #[test]
    fn attaching_a_strategy_returns_a_new_value_and_clears_nothing() {
        let (base, _token) = TurnOptions::cancellable();
        let armed = base.clone().with_round_strategy(Arc::new(Quiet));

        assert!(base.round_strategy.is_none(), "the original is untouched");
        assert!(armed.round_strategy.is_some());
        assert!(armed.cancel.is_some(), "the token survives the strategy");
    }
}