synaps-core 0.10.2

Foundation types, config, session, auth, protocol — leaf crate for agent-runtime
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
759
760
//! Pure, task-aware context pressure policy. No I/O, clocks, prompts, or tools.
//!
//! Pressure is preparation, not a percentage-based stop. Existing execution
//! can continue through the warning band, but a new task or execution after a
//! plan should start in fresh context. At rollover only a bounded Plan/WrapUp
//! extension is allowed; provider capacity always takes precedence.
//!
//! The host owns token accounting and safe session replacement. Assess before
//! each model round, then persist `assessment.next_state` at that admission
//! checkpoint (not for UI-only polling). It charges one round for each bounded
//! extension. Keep that state across phase reports and mode changes; reset it
//! only after successful context replacement. Neither phase reports nor these
//! decisions authorize tools, disclosures, or mutations of session history.

use crate::core::config::{ContextManagementConfig, ContextManagementMode};

/// Advisory task phase. A report is not evidence of authorization or capacity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WorkPhase {
    #[default]
    Unknown,
    /// Execution already in progress may continue through the pressure band.
    Execute,
    /// Finish a bounded piece of existing work; do not begin another task.
    WrapUp,
    /// Produce a plan/specification, not execute the resulting large plan.
    Plan,
    NewTask,
}

impl WorkPhase {
    pub fn parse(value: &str) -> Option<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "unknown" => Some(Self::Unknown),
            "execute" => Some(Self::Execute),
            "wrap_up" | "wrapup" | "wrap-up" => Some(Self::WrapUp),
            "plan" => Some(Self::Plan),
            "new_task" | "newtask" | "new-task" => Some(Self::NewTask),
            _ => None,
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::Unknown => "unknown",
            Self::Execute => "execute",
            Self::WrapUp => "wrap_up",
            Self::Plan => "plan",
            Self::NewTask => "new_task",
        }
    }
}

/// Per-context state. Private counters prevent phase reports from replenishing
/// the allowance. The host must preserve this state across model rounds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ContextState {
    phase: WorkPhase,
    plan_pending_execution: bool,
    boundary_pending: bool,
    rollover_due: bool,
    rollover_required: bool,
    finish_rounds_used: u32,
    /// Host-recorded failed-to-shrink attempt: (input footprint, skipped rounds).
    /// Advisory phases never clear this; hard admission is checked first.
    unproductive_rollover: Option<(u64, u8)>,
}

impl ContextState {
    pub fn phase(&self) -> WorkPhase {
        self.phase
    }

    pub fn finish_rounds_used(&self) -> u32 {
        self.finish_rounds_used
    }

    /// Record advisory progress. Intermediate Unknown/WrapUp reports cannot
    /// hide a Plan -> Execute transition, nor can reports reset an extension.
    pub fn report_phase(&mut self, phase: WorkPhase) {
        match phase {
            WorkPhase::Plan => self.plan_pending_execution = true,
            WorkPhase::Execute if self.plan_pending_execution => {
                self.boundary_pending = true;
                self.plan_pending_execution = false;
            }
            WorkPhase::NewTask => self.boundary_pending = true,
            _ => {}
        }
        self.phase = phase;
    }

    /// Host-only: candidate cannot meaningfully shrink, but the current full
    /// request still passes hard admission. Keep task/finish state intact and
    /// avoid a no-op archive/rollover loop. Reassess after bounded progress.
    pub fn defer_unproductive_rollover(&mut self, used_tokens: u64) {
        self.unproductive_rollover = Some((used_tokens, 0));
    }

    /// Host-only lifecycle operation after successful context replacement.
    pub fn reset(&mut self) {
        *self = Self::default();
    }
}

/// Host-supplied, conservative accounting for the next request.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ContextBudget {
    pub context_window_tokens: u64,
    /// Current full input footprint, including system/tool/summary overhead.
    pub used_tokens: u64,
    /// Remaining usable capacity according to the host/provider. May be less
    /// than window - used; a larger value never enlarges the physical window.
    pub hard_remaining_tokens: u64,
    /// Required headroom for the next round, including output/thinking/tool
    /// growth. Compared with (not added to) the configured minimum reserve.
    pub required_next_round_tokens: u64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ContextThresholds {
    pub pressure_tokens: u64,
    pub rollover_tokens: u64,
}

impl ContextThresholds {
    /// Anchored absolute soft bands: 140k/180k at 200k, 250k/400k at 1m.
    /// Interpolate between anchors and cap above 1m. Smaller models scale
    /// down to fit their window. A lone override preserves that explicit
    /// value and moves the other default only if ordering requires it.
    pub fn resolve(
        config: &ContextManagementConfig,
        context_window_tokens: u64,
    ) -> Result<Self, &'static str> {
        config.validate_for_window(context_window_tokens)?;
        let window = context_window_tokens;
        let (pressure, rollover) = if window <= 200_000 {
            ((window * 7 / 10).max(1), (window * 9 / 10).max(2))
        } else if window < 1_000_000 {
            let extra = window - 200_000;
            (
                140_000 + extra * 110_000 / 800_000,
                180_000 + extra * 220_000 / 800_000,
            )
        } else {
            (250_000, 400_000)
        };
        let (pressure_tokens, rollover_tokens) =
            match (config.pressure_tokens, config.rollover_tokens) {
                (Some(p), Some(r)) => (p, r),
                (Some(p), None) => (p, rollover.max(p + 1)),
                (None, Some(r)) => (pressure.min(r - 1), r),
                (None, None) => (pressure, rollover),
            };
        Ok(Self {
            pressure_tokens,
            rollover_tokens,
        })
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContextBand {
    Normal,
    Pressure,
    Rollover,
    HardLimit,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContextAction {
    Disabled,
    Continue,
    /// Preparation only; the current task is not forcibly interrupted.
    Advisory,
    /// Admit one Plan/WrapUp round. Count is the allowance AFTER this round.
    FinishBounded {
        rounds_remaining: u32,
    },
    /// Request host-controlled rollover at a safe boundary, before more work.
    Rollover,
    /// No further model round, even to finish a plan or generate a summary.
    /// The host must recover without exceeding the supplied hard budget.
    HardStop,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContextReason {
    ModeOff,
    BelowPressure,
    PrepareForRollover,
    TaskBoundary,
    RolloverThreshold,
    BoundedFinish,
    FinishAllowanceExhausted,
    RolloverPending,
    UnproductiveRollover,
    HardCapacity,
    InvalidConfig,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ContextAssessment {
    pub action: ContextAction,
    pub band: ContextBand,
    pub reason: ContextReason,
    /// None when disabled, invalid, or already stopped by the hard budget.
    pub thresholds: Option<ContextThresholds>,
    /// Persist at the host's admission checkpoint, even if the action stops
    /// work. Repeated assessments alone have no side effects.
    pub next_state: ContextState,
}

/// Pure assessment, independent of UI, model prose, and tool authority.
/// Hard capacity wins even in Off mode. Invalid programmatic configuration
/// fails closed; config-file validation normally catches it before this call.
pub fn assess_context(
    config: &ContextManagementConfig,
    state: &ContextState,
    budget: ContextBudget,
) -> ContextAssessment {
    let mut assessment = ContextAssessment {
        action: ContextAction::HardStop,
        band: ContextBand::HardLimit,
        reason: ContextReason::HardCapacity,
        thresholds: None,
        next_state: *state,
    };
    let remaining = budget.hard_remaining_tokens.min(
        budget
            .context_window_tokens
            .saturating_sub(budget.used_tokens),
    );
    let required = budget.required_next_round_tokens.max(config.reserve_tokens);
    if remaining == 0 || remaining < required {
        return assessment;
    }

    // Consume boundary reports at the admission checkpoint, including Off
    // mode, so an old low-pressure transition does not interrupt later work.
    assessment.next_state.boundary_pending = false;
    if config.mode == ContextManagementMode::Off {
        assessment.action = ContextAction::Disabled;
        assessment.band = ContextBand::Normal;
        assessment.reason = ContextReason::ModeOff;
        return assessment;
    }
    let Ok(thresholds) = ContextThresholds::resolve(config, budget.context_window_tokens) else {
        assessment.reason = ContextReason::InvalidConfig;
        return assessment;
    };
    assessment.thresholds = Some(thresholds);
    assessment.band = if budget.used_tokens >= thresholds.rollover_tokens {
        ContextBand::Rollover
    } else if budget.used_tokens >= thresholds.pressure_tokens {
        ContextBand::Pressure
    } else {
        ContextBand::Normal
    };

    // Hard admission and configuration validation above always win. A soft
    // no-shrink result may admit work, never renew finish/time/cost allowances.
    // Retry on changed footprint (growth OR reduction), otherwise after four
    // provider admissions so a newly archivable tail is eventually reconsidered.
    if let Some((used, skipped)) = state.unproductive_rollover {
        if budget.used_tokens.abs_diff(used) < 8_192 && skipped < 4 {
            assessment.next_state.unproductive_rollover = Some((used, skipped + 1));
            assessment.action = ContextAction::Advisory;
            assessment.reason = ContextReason::UnproductiveRollover;
            return assessment;
        }
        assessment.next_state.unproductive_rollover = None;
    }

    if state.rollover_required {
        assessment.action = ContextAction::Rollover;
        assessment.reason = ContextReason::RolloverPending;
        return assessment;
    }
    if budget.used_tokens >= thresholds.pressure_tokens
        && (state.boundary_pending || state.phase == WorkPhase::NewTask)
    {
        assessment.next_state.rollover_required = true;
        assessment.action = ContextAction::Rollover;
        assessment.reason = ContextReason::TaskBoundary;
        return assessment;
    }
    if assessment.band == ContextBand::Rollover || state.rollover_due {
        // Token-estimate decreases, repeated reports, or mode toggles cannot
        // renew an allowance once this context has entered rollover.
        assessment.next_state.rollover_due = true;
        if matches!(state.phase, WorkPhase::Plan | WorkPhase::WrapUp)
            && state.finish_rounds_used < config.finish_rounds
        {
            assessment.next_state.finish_rounds_used += 1;
            assessment.action = ContextAction::FinishBounded {
                rounds_remaining: config.finish_rounds - assessment.next_state.finish_rounds_used,
            };
            assessment.reason = ContextReason::BoundedFinish;
        } else {
            assessment.next_state.rollover_required = true;
            assessment.action = ContextAction::Rollover;
            assessment.reason = if state.finish_rounds_used >= config.finish_rounds {
                ContextReason::FinishAllowanceExhausted
            } else {
                ContextReason::RolloverThreshold
            };
        }
    } else if assessment.band == ContextBand::Pressure {
        assessment.action = ContextAction::Advisory;
        assessment.reason = ContextReason::PrepareForRollover;
    } else {
        assessment.action = ContextAction::Continue;
        assessment.reason = ContextReason::BelowPressure;
    }
    assessment
}

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

    fn auto_config() -> ContextManagementConfig {
        ContextManagementConfig {
            mode: ContextManagementMode::Auto,
            ..Default::default()
        }
    }

    fn budget(window: u64, used: u64) -> ContextBudget {
        ContextBudget {
            context_window_tokens: window,
            used_tokens: used,
            hard_remaining_tokens: window.saturating_sub(used),
            required_next_round_tokens: 8_000,
        }
    }

    #[test]
    fn unproductive_rollover_defers_only_soft_admission_and_retries_after_progress() {
        let config = auto_config();
        let mut state = ContextState::default();
        state.report_phase(WorkPhase::NewTask);
        state = assess_context(&config, &state, budget(1_000_000, 339_058)).next_state;
        state.defer_unproductive_rollover(339_058);
        for _ in 0..4 {
            state.report_phase(WorkPhase::NewTask); // repeated model reports cannot clear cooldown
            let next = assess_context(&config, &state, budget(1_000_000, 339_100));
            assert_eq!(next.action, ContextAction::Advisory);
            assert_eq!(next.reason, ContextReason::UnproductiveRollover);
            state = next.next_state;
        }
        assert_eq!(
            assess_context(&config, &state, budget(1_000_000, 339_100)).action,
            ContextAction::Rollover
        );
        for changed in [329_000, 350_000] {
            state.defer_unproductive_rollover(339_058);
            assert_eq!(
                assess_context(&config, &state, budget(1_000_000, changed)).action,
                ContextAction::Rollover
            );
        }
        state.reset();
        assert_eq!(state.unproductive_rollover, None);
        assert_eq!(state.phase(), WorkPhase::Unknown);
    }

    #[test]
    fn unproductive_cooldown_cannot_bypass_hard_budget_or_renew_finish_allowance() {
        let config = auto_config();
        let mut state = ContextState::default();
        state.report_phase(WorkPhase::Plan);
        for _ in 0..config.finish_rounds {
            state = assess_context(&config, &state, budget(1_000_000, 400_000)).next_state;
        }
        state = assess_context(&config, &state, budget(1_000_000, 400_000)).next_state;
        state.defer_unproductive_rollover(400_000);
        state.report_phase(WorkPhase::WrapUp);
        let off = ContextManagementConfig {
            mode: ContextManagementMode::Off,
            ..config
        };
        state = assess_context(&off, &state, budget(1_000_000, 400_000)).next_state;
        assert_eq!(state.unproductive_rollover, Some((400_000, 0)));
        assert_eq!(state.finish_rounds_used(), config.finish_rounds);
        let denied = assess_context(
            &config,
            &state,
            ContextBudget {
                hard_remaining_tokens: 0,
                ..budget(1_000_000, 400_000)
            },
        );
        assert_eq!(denied.action, ContextAction::HardStop);
        assert_eq!(denied.next_state, state);
        assert_eq!(
            assess_context(&config, &state, budget(410_000, 400_000)).action,
            ContextAction::HardStop
        );
        let allowed = assess_context(&config, &state, budget(1_000_000, 400_000));
        assert_eq!(allowed.reason, ContextReason::UnproductiveRollover);
        assert_eq!(
            allowed.next_state.finish_rounds_used(),
            config.finish_rounds
        );
    }

    #[test]
    fn context_threshold_anchors_and_pressure_are_advisory() {
        let config = auto_config();
        for (window, pressure, rollover) in [
            (200_000, 140_000, 180_000),
            (1_000_000, 250_000, 400_000),
            (2_000_000, 250_000, 400_000),
        ] {
            assert_eq!(
                ContextThresholds::resolve(&config, window).unwrap(),
                ContextThresholds {
                    pressure_tokens: pressure,
                    rollover_tokens: rollover
                }
            );
            let mut state = ContextState::default();
            state.report_phase(WorkPhase::Execute);
            assert_eq!(
                assess_context(&config, &state, budget(window, pressure - 1)).action,
                ContextAction::Continue
            );
            let at_pressure = assess_context(&config, &state, budget(window, pressure));
            assert_eq!(at_pressure.action, ContextAction::Advisory);
            assert_eq!(at_pressure.band, ContextBand::Pressure);
            assert_eq!(
                assess_context(&config, &state, budget(window, rollover - 1)).action,
                ContextAction::Advisory
            );
            assert_eq!(
                assess_context(&config, &state, budget(window, rollover)).action,
                ContextAction::Rollover
            );
        }
    }

    #[test]
    fn context_350k_plan_finishes_before_execute_requests_rollover() {
        let config = auto_config();
        let current_budget = budget(1_000_000, 350_000);
        for phase in [WorkPhase::Execute, WorkPhase::WrapUp, WorkPhase::Plan] {
            let mut state = ContextState::default();
            state.report_phase(phase);
            assert_eq!(
                assess_context(&config, &state, current_budget).action,
                ContextAction::Advisory
            );
        }
        let mut state = ContextState::default();
        state.report_phase(WorkPhase::Plan);
        state = assess_context(&config, &state, current_budget).next_state;
        state.report_phase(WorkPhase::Unknown);
        state.report_phase(WorkPhase::WrapUp);
        state.report_phase(WorkPhase::Execute);
        state.report_phase(WorkPhase::Plan); // cannot hide the boundary
        let assessment = assess_context(&config, &state, current_budget);
        assert_eq!(assessment.action, ContextAction::Rollover);
        assert_eq!(assessment.reason, ContextReason::TaskBoundary);
        state = assessment.next_state;
        state.report_phase(WorkPhase::WrapUp);
        assert_eq!(
            assess_context(&config, &state, current_budget).action,
            ContextAction::Rollover
        );
        state.reset();
        assert_eq!(
            assess_context(&config, &state, budget(1_000_000, 0)).action,
            ContextAction::Continue
        );
    }

    #[test]
    fn context_new_task_rolls_over_at_pressure_not_before() {
        let config = auto_config();
        let mut state = ContextState::default();
        state.report_phase(WorkPhase::NewTask);
        assert_eq!(
            assess_context(&config, &state, budget(1_000_000, 249_999)).action,
            ContextAction::Continue
        );
        assert_eq!(
            assess_context(&config, &state, budget(1_000_000, 250_000)).action,
            ContextAction::Rollover
        );
    }

    #[test]
    fn context_low_pressure_boundary_is_consumed_at_admission() {
        let config = auto_config();
        let mut state = ContextState::default();
        state.report_phase(WorkPhase::Plan);
        state.report_phase(WorkPhase::Execute);
        state = assess_context(&config, &state, budget(1_000_000, 100_000)).next_state;
        assert_eq!(
            assess_context(&config, &state, budget(1_000_000, 350_000)).action,
            ContextAction::Advisory
        );
    }

    #[test]
    fn context_400k_finish_is_bounded_across_reports_and_estimate_decreases() {
        let config = auto_config();
        for phase in [WorkPhase::Plan, WorkPhase::WrapUp] {
            let mut state = ContextState::default();
            state.report_phase(phase);
            let first = assess_context(&config, &state, budget(1_000_000, 400_000));
            assert_eq!(
                first.action,
                ContextAction::FinishBounded {
                    rounds_remaining: 1
                }
            );
            assert_eq!(state.finish_rounds_used(), 0); // assessment itself is pure
            assert_eq!(
                first,
                assess_context(&config, &state, budget(1_000_000, 400_000))
            );
            state = first.next_state;
            state.report_phase(WorkPhase::Unknown);
            state.report_phase(phase);
            let second = assess_context(&config, &state, budget(1_000_000, 350_000));
            assert_eq!(
                second.action,
                ContextAction::FinishBounded {
                    rounds_remaining: 0
                }
            );
            state = second.next_state;
            assert_eq!(state.finish_rounds_used(), 2);
            state.report_phase(phase);
            let exhausted = assess_context(&config, &state, budget(1_000_000, 100_000));
            assert_eq!(exhausted.action, ContextAction::Rollover);
            assert_eq!(exhausted.reason, ContextReason::FinishAllowanceExhausted);
            state = exhausted.next_state;
            state.report_phase(WorkPhase::Plan);
            assert_eq!(
                assess_context(&config, &state, budget(1_000_000, 100_000)).action,
                ContextAction::Rollover
            );
            state.reset();
            assert_eq!(state.finish_rounds_used(), 0);
            assert_eq!(state.phase(), WorkPhase::Unknown);
        }
    }

    #[test]
    fn context_finish_override_is_bounded_including_zero() {
        for limit in [0, 1, ContextManagementConfig::MAX_FINISH_ROUNDS] {
            let config = ContextManagementConfig {
                finish_rounds: limit,
                ..auto_config()
            };
            let mut state = ContextState::default();
            state.report_phase(WorkPhase::WrapUp);
            for used in 0..limit {
                let assessment = assess_context(&config, &state, budget(1_000_000, 400_000));
                assert_eq!(
                    assessment.action,
                    ContextAction::FinishBounded {
                        rounds_remaining: limit - used - 1
                    }
                );
                state = assessment.next_state;
            }
            assert_eq!(
                assess_context(&config, &state, budget(1_000_000, 400_000)).action,
                ContextAction::Rollover
            );
        }
    }

    #[test]
    fn context_off_is_default_and_mode_toggles_do_not_replenish_finish() {
        let off = ContextManagementConfig::default();
        let mut state = ContextState::default();
        state.report_phase(WorkPhase::WrapUp);
        assert_eq!(
            assess_context(&off, &state, budget(1_000_000, 400_000)).action,
            ContextAction::Disabled
        );
        state = assess_context(&auto_config(), &state, budget(1_000_000, 400_000)).next_state;
        state = assess_context(&off, &state, budget(1_000_000, 410_000)).next_state;
        assert_eq!(state.finish_rounds_used(), 1);
        let second = assess_context(&auto_config(), &state, budget(1_000_000, 420_000));
        assert_eq!(
            second.action,
            ContextAction::FinishBounded {
                rounds_remaining: 0
            }
        );
        assert_eq!(
            assess_context(
                &auto_config(),
                &second.next_state,
                budget(1_000_000, 420_000)
            )
            .action,
            ContextAction::Rollover
        );
    }

    #[test]
    fn context_hard_capacity_wins_for_every_phase_and_mode() {
        for mode in [ContextManagementMode::Off, ContextManagementMode::Auto] {
            let config = ContextManagementConfig {
                mode,
                ..Default::default()
            };
            for phase in [
                WorkPhase::Unknown,
                WorkPhase::Execute,
                WorkPhase::WrapUp,
                WorkPhase::Plan,
                WorkPhase::NewTask,
            ] {
                let mut state = ContextState::default();
                state.report_phase(phase);
                for hard_budget in [
                    ContextBudget {
                        hard_remaining_tokens: 15_999,
                        ..budget(1_000_000, 350_000)
                    },
                    ContextBudget {
                        required_next_round_tokens: 650_001,
                        ..budget(1_000_000, 350_000)
                    },
                    ContextBudget {
                        hard_remaining_tokens: u64::MAX,
                        ..budget(200_000, 190_000)
                    },
                    budget(200_000, 200_001),
                    budget(0, 0),
                ] {
                    let assessment = assess_context(&config, &state, hard_budget);
                    assert_eq!(
                        assessment.action,
                        ContextAction::HardStop,
                        "{mode:?} {phase:?} {hard_budget:?}"
                    );
                    assert_eq!(assessment.band, ContextBand::HardLimit);
                    assert_eq!(assessment.reason, ContextReason::HardCapacity);
                    assert_eq!(assessment.next_state, state);
                }
            }
        }
    }

    #[test]
    fn context_exact_reserve_is_allowed_and_next_round_can_require_more() {
        let config = auto_config();
        let state = ContextState::default();
        let exact = ContextBudget {
            hard_remaining_tokens: 16_000,
            ..budget(200_000, 140_000)
        };
        assert_eq!(
            assess_context(&config, &state, exact).action,
            ContextAction::Advisory
        );
        let larger = ContextBudget {
            required_next_round_tokens: 16_001,
            ..exact
        };
        assert_eq!(
            assess_context(&config, &state, larger).action,
            ContextAction::HardStop
        );
    }

    #[test]
    fn context_threshold_overrides_preserve_explicit_values() {
        for (pressure, rollover, expected) in [
            (Some(350_000), Some(500_000), (350_000, 500_000)),
            (Some(450_000), None, (450_000, 450_001)),
            (None, Some(200_000), (199_999, 200_000)),
        ] {
            let config = ContextManagementConfig {
                pressure_tokens: pressure,
                rollover_tokens: rollover,
                ..auto_config()
            };
            let thresholds = ContextThresholds::resolve(&config, 1_000_000).unwrap();
            assert_eq!(
                (thresholds.pressure_tokens, thresholds.rollover_tokens),
                expected
            );
        }
        assert!(ContextThresholds::resolve(&auto_config(), u64::MAX).is_ok());
        assert_eq!(
            ContextThresholds::resolve(&auto_config(), 100_000)
                .unwrap()
                .pressure_tokens,
            70_000
        );
        assert_eq!(
            ContextThresholds::resolve(&auto_config(), 600_000)
                .unwrap()
                .rollover_tokens,
            290_000
        );
    }

    #[test]
    fn context_invalid_programmatic_config_fails_closed() {
        for config in [
            ContextManagementConfig {
                pressure_tokens: Some(0),
                ..auto_config()
            },
            ContextManagementConfig {
                pressure_tokens: Some(u64::MAX),
                ..auto_config()
            },
            ContextManagementConfig {
                rollover_tokens: Some(1_000_001),
                ..auto_config()
            },
            ContextManagementConfig {
                finish_rounds: 9,
                ..auto_config()
            },
            ContextManagementConfig {
                reserve_tokens: 0,
                ..auto_config()
            },
        ] {
            let assessment = assess_context(
                &config,
                &ContextState::default(),
                budget(1_000_000, 350_000),
            );
            assert_eq!(assessment.action, ContextAction::HardStop);
            assert_eq!(assessment.reason, ContextReason::InvalidConfig);
        }
    }

    #[test]
    fn context_work_phase_roundtrips_and_rejects_unknown_reports() {
        for phase in [
            WorkPhase::Unknown,
            WorkPhase::Execute,
            WorkPhase::WrapUp,
            WorkPhase::Plan,
            WorkPhase::NewTask,
        ] {
            assert_eq!(WorkPhase::parse(phase.as_str()), Some(phase));
        }
        assert_eq!(WorkPhase::parse(" PLAN "), Some(WorkPhase::Plan));
        assert_eq!(WorkPhase::parse("wrap-up"), Some(WorkPhase::WrapUp));
        assert_eq!(WorkPhase::parse("new-task"), Some(WorkPhase::NewTask));
        assert_eq!(WorkPhase::parse("finish_forever"), None);
    }
}