newt-core 0.8.0

Newt-Agent core types, errors, and the NeMoCode-style tier router
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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
//! Sticky user preferences (`~/.newt/settings.toml`).
//!
//! A small, hand-editable file that records the *last-active* session
//! selections so the next `newt` invocation starts where you left off
//! (issue #545). Today that means two axes, both under `[session]`:
//!
//! ```toml
//! # newt — sticky user preferences (hand-editable).
//! [session]
//! provider = "dgx1"      # last `/backends <name>`
//! model = "gpt-4.1"      # last `/model <name>`
//! ```
//!
//! It is written automatically when you switch the backend (`/backends
//! <name>`) or the model (`/model <name>`) in the TUI, and read once at
//! startup to seed `NEWT_PROVIDER` / `NEWT_DGX_MODEL`.
//!
//! # Per project
//!
//! A switch is remembered **per project**, so changing backend in one repo
//! does not move every other repo. The choice lives in this operator-owned
//! file — never in the repo, whose overlay cannot set a backend — as a bounded
//! table keyed by the canonical repo root:
//!
//! ```toml
//! [projects."/path/to/repo"]
//! provider = "dgx1"
//! used = 7
//! ```
//!
//! An entry exists only while it differs from the global `[session]` choice
//! (or the default backend), is dropped when switched back, is capped at
//! [`MAX_PROJECTS`] with least-recently-switched eviction (a start never writes), and is pruned when its
//! path no longer exists. `[session]` is now hand-set: the app no longer
//! writes it.
//!
//! # Design
//!
//! * **Lowest precedence on restore.** An explicit `NEWT_PROVIDER` /
//!   `NEWT_DGX_MODEL` in the environment, or a `--loadout`'s provider/model
//!   axis, always wins. `settings.toml` only fills an axis nothing else
//!   pinned ([`Session::restore`]).
//! * **Defensive.** A `provider` naming a `[[backends]]` entry that no longer
//!   exists is ignored, so editing config out from under the file can never
//!   break startup.
//! * **Hand-editable + room to grow.** Reads/writes go through a dynamic
//!   [`toml::Table`], so unknown keys and tables the user (or a future newt)
//!   adds are preserved across an in-app rewrite. The one thing a rewrite
//!   does *not* preserve is inline comments — keep durable notes in
//!   `config.toml`; this file's header says so.
//!
//! This is deliberately separate from the hand-authored `~/.newt/config.toml`:
//! config is where you *declare* backends/loadouts; `settings.toml` is the
//! lean, machine-managed memory of what you last picked.

use std::path::{Path, PathBuf};

/// Path to `~/.newt/settings.toml` (sibling of `config.toml`).
pub fn settings_path() -> Option<PathBuf> {
    crate::config::Config::user_config_path().map(|p| p.with_file_name("settings.toml"))
}

/// The last-active selections read from the `[session]` table.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Session {
    /// Last `[[backends]]` name chosen via `/backends <name>`.
    pub provider: Option<String>,
    /// Last model override chosen via `/model <name>` (the `NEWT_DGX_MODEL` axis).
    pub model: Option<String>,
    /// True when `model` came from THIS project's OWN `settings.toml` entry
    /// rather than the global `[session]` table (#2622 EVIDENCE). A project
    /// entry records a bare model with no `provider` key whenever the model
    /// was picked while already on the project's active backend (`Choice::
    /// Model` in `apply_project_choice`) — `self.provider` then inherits the
    /// GLOBAL session provider, which drifts independently (e.g. a later
    /// `/backends` switch elsewhere, or simply going stale) and need not
    /// match the backend actually in use. Gating restore on that inherited,
    /// possibly-stale value dropped the project's own remembered model every
    /// time it disagreed with the real active backend. A project-scoped
    /// model restores whenever the project is active, full stop; only a
    /// GLOBAL model (no project entry) still needs the provider-match guard
    /// in [`Self::restore`], because that's the only case where the
    /// model/provider coupling actually means something.
    model_from_project: bool,
}

/// The startup environment a [`Session`] asks for: each field is `Some` only
/// when that axis should actually be set (nothing already pinned it, and — for
/// `provider` — the named backend still exists).
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Restore {
    pub provider: Option<String>,
    pub model: Option<String>,
}

impl Session {
    /// Extract `[session]` selections from a parsed settings document. Tolerant
    /// of a missing table, missing keys, non-string values, and empty strings
    /// (all read as `None`) — a malformed file must never break startup.
    pub fn from_doc(doc: &toml::Table) -> Self {
        let session = doc.get("session").and_then(toml::Value::as_table);
        let read = |key: &str| {
            session
                .and_then(|t| t.get(key))
                .and_then(toml::Value::as_str)
                .map(str::to_string)
                .filter(|s| !s.is_empty())
        };
        Self {
            provider: read("provider"),
            model: read("model"),
            model_from_project: false,
        }
    }

    /// True when nothing is recorded (skip the whole restore/write dance).
    pub fn is_empty(&self) -> bool {
        self.provider.is_none() && self.model.is_none()
    }

    /// The global `[session]` choice overlaid by `project`'s entry, if any. An
    /// entry that names a provider owns the model too (a model belongs to the
    /// provider it was chosen under, so the global model never bleeds onto it).
    pub fn for_project(doc: &toml::Table, project: &str) -> Self {
        let global = Self::from_doc(doc);
        let Some(entry) = project_entry(doc, project) else {
            return global;
        };
        let (provider, model) = (entry.provider, entry.model);
        // Only a BARE project model (no provider of its own) is the "picked
        // while already active" case the field exists for (#2626 review
        // P1-2). An entry that names its OWN provider couples model to that
        // provider exactly like the global table does, so it must keep
        // going through the ordinary provider-match guard in `restore`.
        let model_from_project = model.is_some() && provider.is_none();
        Self {
            model: match (&provider, model) {
                (_, Some(m)) => Some(m),
                (Some(_), None) => None,
                (None, None) => global.model,
            },
            provider: provider.or(global.provider),
            model_from_project,
        }
    }

    /// Decide what to restore. `current_provider` is the value `NEWT_PROVIDER`
    /// already holds (an explicit env var or a `--loadout`'s provider) — `None`
    /// if unset; a pinned provider is left untouched. `model_pinned` is whether
    /// `NEWT_DGX_MODEL` is already set. `known_backend` guards the recorded
    /// provider so a stale name (backend since removed from config) is dropped
    /// rather than producing a dangling pin. Pure — the caller owns the env and
    /// config lookups, keeping this fully unit-testable.
    ///
    /// A recorded model belongs to the provider it was chosen under
    /// (`self.provider`), so it is restored only when that provider is the one
    /// that will actually be active. This keeps a model picked for one backend
    /// from bleeding onto a *different* backend selected by env or a `--loadout`
    /// — matching the in-app rule that picking a provider clears the model
    /// override. (When both are `None` the model was chosen on the default
    /// backend, which is also what's active, so a bare `/model` choice still
    /// sticks.) #2622: this guard applies ONLY to a global model —
    /// `self.model_from_project` restores unconditionally whenever its project
    /// is active, since it was never coupled to a provider in the first place
    /// (see that field's doc comment).
    pub fn restore(
        &self,
        current_provider: Option<&str>,
        model_pinned: bool,
        known_backend: impl Fn(&str) -> bool,
    ) -> Restore {
        // Provider: fill it only when nothing already pinned one and the
        // recorded name still resolves to a configured backend.
        let provider = match current_provider {
            Some(_) => None,
            None => self
                .provider
                .as_deref()
                .filter(|name| known_backend(name))
                .map(str::to_string),
        };
        // The provider that will be active once our decision lands: an existing
        // pin, else the one we just restored, else the default resolution.
        let effective = current_provider.or(provider.as_deref());
        let model = self
            .model
            .as_deref()
            .filter(|_| !model_pinned)
            .filter(|_| self.model_from_project || effective == self.provider.as_deref())
            .map(str::to_string);
        Restore { provider, model }
    }
}

/// Whether a `/backends`/`/model` switch should be persisted to
/// `settings.toml`. `false` in an ephemeral session (`--ephemeral` /
/// `NEWT_EPHEMERAL`), which must leave no trace on disk — the switch still
/// applies live for the session, it just isn't recorded. Pure mirror of the
/// `should_extract_on_close` rule; the caller computes `ephemeral` from the env.
pub fn should_persist(ephemeral: bool) -> bool {
    !ephemeral
}

/// Most per-project entries kept; the least recently switched is evicted first.
pub const MAX_PROJECTS: usize = 32;

/// One `[projects.<root>]` entry: the axes that differ from the global choice.
struct Entry {
    provider: Option<String>,
    model: Option<String>,
}

fn project_entry(doc: &toml::Table, project: &str) -> Option<Entry> {
    let t = doc.get("projects")?.as_table()?.get(project)?.as_table()?;
    let read = |k: &str| {
        t.get(k)
            .and_then(toml::Value::as_str)
            .filter(|s| !s.is_empty())
            .map(str::to_string)
    };
    Some(Entry {
        provider: read("provider"),
        model: read("model"),
    })
}

/// A `/backends` or `/model` switch, to be recorded for one project.
#[derive(Debug, Clone, Copy)]
pub enum Choice<'a> {
    Provider(&'a str),
    Model(&'a str),
}

/// Record `choice` for `project` in `doc`: keep only what differs from the
/// global `[session]` choice (`default_provider` is the config default backend,
/// the baseline when `[session]` names none), drop the entry when nothing does,
/// then prune paths that no longer `exist` and evict least-recently-switched beyond
/// [`MAX_PROJECTS`]. Pure over `doc` so it unit-tests without a filesystem.
pub fn apply_project_choice(
    doc: &mut toml::Table,
    project: &str,
    choice: Choice<'_>,
    default_provider: Option<&str>,
    exists: impl Fn(&str) -> bool,
) {
    let global = Session::from_doc(doc);
    let old = project_entry(doc, project);
    let old_provider = old.and_then(|e| e.provider);
    // A provider switch clears the model, as in-session.
    let (mut provider, mut model) = match choice {
        Choice::Provider(name) => (Some(name.to_string()), None),
        Choice::Model(name) => (old_provider, Some(name.to_string())),
    };
    let baseline = global.provider.as_deref().or(default_provider);
    if provider.as_deref() == baseline {
        provider = None;
    }
    if provider.is_none() && model == global.model {
        model = None;
    }
    let projects = doc
        .entry("projects".to_string())
        .or_insert_with(|| toml::Value::Table(toml::Table::new()));
    if !projects.is_table() {
        *projects = toml::Value::Table(toml::Table::new());
    }
    let Some(projects) = projects.as_table_mut() else {
        return;
    };
    projects.retain(|path, _| exists(path));
    let used = |v: &toml::Value| v.get("used").and_then(toml::Value::as_integer).unwrap_or(0);
    let tick = projects.values().map(used).max().unwrap_or(0) + 1;
    projects.remove(project);
    if provider.is_some() || model.is_some() {
        let mut t = toml::Table::new();
        for (k, v) in [("provider", provider), ("model", model)] {
            if let Some(v) = v {
                t.insert(k.into(), toml::Value::String(v));
            }
        }
        t.insert("used".into(), toml::Value::Integer(tick));
        projects.insert(project.to_string(), toml::Value::Table(t));
    }
    while projects.len() > MAX_PROJECTS {
        let Some(lru) = projects
            .iter()
            .min_by_key(|(_, v)| used(v))
            .map(|(k, _)| k.clone())
        else {
            break;
        };
        projects.remove(&lru);
    }
    if projects.is_empty() {
        doc.remove("projects");
    }
}

/// The self-documenting header re-emitted on every write. (Comments inside the
/// body are not round-tripped through [`toml::Table`]; this header always is.)
const HEADER: &str = "\
# newt — sticky user preferences (hand-editable).
#
# Auto-updated when you switch the backend (/backends <name>) or model
# (/model <name>) in the TUI: the choice is remembered PER PROJECT, under
# [projects.\"<repo root>\"], and restored the next time newt starts there.
# Only choices that differ from [session] (your own default, hand-set) are
# kept; at most 32 projects, least recently SWITCHED dropped (reads never touch it), missing (or unmounted) paths pruned.
# Restore is the LOWEST precedence: an explicit NEWT_PROVIDER / NEWT_DGX_MODEL
# in the environment, a --backend-* flag or a --loadout, or a resumed
# conversation's pin, always wins. Delete this file to forget every choice.
#
# Hand-editable, but note: an in-app /backends or /model write preserves other
# keys/tables yet drops inline comments — keep durable notes in config.toml.
";

/// Set (`Some`) or clear (`None`) `session.<key>` in a settings document,
/// preserving every other key and table. Clearing the last key in `[session]`
/// drops the now-empty table so the file stays tidy. Pure (operates on the
/// passed document) so it unit-tests without touching the filesystem.
pub fn apply_session_key(doc: &mut toml::Table, key: &str, value: Option<&str>) {
    match value {
        Some(v) => {
            let entry = doc
                .entry("session".to_string())
                .or_insert_with(|| toml::Value::Table(toml::Table::new()));
            // Heal a `session` key the user mistyped as a non-table.
            if !entry.is_table() {
                *entry = toml::Value::Table(toml::Table::new());
            }
            if let Some(table) = entry.as_table_mut() {
                table.insert(key.to_string(), toml::Value::String(v.to_string()));
            }
        }
        None => {
            if let Some(toml::Value::Table(table)) = doc.get_mut("session") {
                table.remove(key);
                if table.is_empty() {
                    doc.remove("session");
                }
            }
        }
    }
}

/// Render a settings document to TOML text with the header. Returns `Err` (so
/// the caller skips the write rather than truncating the file) if the document
/// cannot be serialized.
pub fn to_toml_string(doc: &toml::Table) -> Result<String, toml::ser::Error> {
    Ok(format!("{HEADER}{}", toml::to_string_pretty(doc)?))
}

// ---------------------------------------------------------------------------
// Filesystem seam (thin; integration-tier only — never exercised by unit tests
// per the repo test-fs policy, mirroring `tuning.rs`).
// ---------------------------------------------------------------------------

/// Parse the settings document at `path` into a dynamic table. Any error
/// (absent file, parse failure) yields an empty document.
fn read_doc(path: &Path) -> toml::Table {
    std::fs::read_to_string(path)
        .ok()
        .and_then(|text| toml::from_str::<toml::Table>(&text).ok())
        .unwrap_or_default()
}

/// Write the document back, creating `~/.newt/` if needed. A serialization
/// failure is surfaced as an error *before* any write, so a broken document
/// never truncates the file.
fn write_doc(path: &Path, doc: &toml::Table) -> std::io::Result<()> {
    let text = to_toml_string(doc).map_err(|e| std::io::Error::other(e.to_string()))?;
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir)?;
    }
    std::fs::write(path, text)
}

/// The repo root for `cwd`: the parent of the nearest ancestor `.git` (a dir,
/// or a linked worktree's file), else `cwd`. Pure over the injected `exists`.
fn root_for(cwd: &Path, exists: impl Fn(&Path) -> bool) -> PathBuf {
    crate::config::find_ancestor_dir(cwd, Path::new(".git"), exists)
        .and_then(|git| git.parent().map(Path::to_path_buf))
        .unwrap_or_else(|| cwd.to_path_buf())
}

/// The session's workspace, when it is not the process cwd (`newt headless
/// --cwd DIR`). ponytail: process-wide instead of threading a parameter through
/// every `/backends`/`/model` call site; one session per process.
static WORKSPACE: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);

/// Declare the session workspace so the per-project key follows it, not the
/// directory the process happened to be launched from.
pub fn set_workspace(dir: &Path) {
    if let Ok(mut w) = WORKSPACE.lock() {
        *w = Some(dir.to_path_buf());
    }
}

/// The project root for `workspace` (else `cwd`). Pure over `exists`.
fn key_for(workspace: Option<&Path>, cwd: &Path, exists: impl Fn(&Path) -> bool) -> PathBuf {
    root_for(workspace.unwrap_or(cwd), exists)
}

/// The canonical project root of the session workspace (no subprocess).
fn project_key() -> Option<String> {
    let cwd = std::env::current_dir().ok()?;
    let ws = WORKSPACE.lock().ok().and_then(|w| w.clone());
    let root = key_for(ws.as_deref(), &cwd, |p| p.exists());
    Some(
        root.canonicalize()
            .unwrap_or(root)
            .to_string_lossy()
            .into_owned(),
    )
}

/// Load the selections for the current project (global `[session]` overlaid by
/// this project's entry) from `~/.newt/settings.toml`. Empty on any error.
pub fn load() -> Session {
    let Some(path) = settings_path() else {
        return Session::default();
    };
    let doc = read_doc(&path);
    match project_key() {
        Some(key) => Session::for_project(&doc, &key),
        None => Session::from_doc(&doc),
    }
}

/// Read-modify-write `~/.newt/settings.toml` for the current project,
/// preserving unknown content. Best-effort: a path we can't resolve or a write
/// we can't perform is a no-op.
fn update(choice: Choice<'_>, default_provider: Option<&str>) {
    let (Some(path), Some(key)) = (settings_path(), project_key()) else {
        return;
    };
    let mut doc = read_doc(&path);
    apply_project_choice(&mut doc, &key, choice, default_provider, |p| {
        Path::new(p).exists()
    });
    let _ = write_doc(&path, &doc);
}

/// Persist the provider chosen via `/backends <name>` for this project,
/// clearing any stale model override (mirrors the session's `NEWT_DGX_MODEL`
/// reset). `default_provider` is the config's default backend. Best-effort.
pub fn record_provider(name: &str, default_provider: Option<&str>) {
    update(Choice::Provider(name), default_provider);
}

/// Persist the model chosen via `/model <name>` for this project (leaving the
/// provider as-is). Best-effort.
pub fn record_model(name: &str, default_provider: Option<&str>) {
    update(Choice::Model(name), default_provider);
}

// ---------------------------------------------------------------------------
// Tests — pure / in-memory only (no real filesystem, per the test-fs policy).
// ---------------------------------------------------------------------------

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

    fn doc(text: &str) -> toml::Table {
        toml::from_str(text).expect("valid toml")
    }

    #[test]
    fn from_doc_reads_session_axes() {
        let d = doc("[session]\nprovider = \"dgx1\"\nmodel = \"gpt-4.1\"\n");
        let s = Session::from_doc(&d);
        assert_eq!(s.provider.as_deref(), Some("dgx1"));
        assert_eq!(s.model.as_deref(), Some("gpt-4.1"));
        assert!(!s.is_empty());
    }

    #[test]
    fn from_doc_is_tolerant_of_missing_empty_and_wrong_types() {
        assert!(Session::from_doc(&doc("")).is_empty());
        assert!(Session::from_doc(&doc("[other]\nx = 1\n")).is_empty());
        // Empty string and non-string value both read as None.
        let d = doc("[session]\nprovider = \"\"\nmodel = 42\n");
        assert!(Session::from_doc(&d).is_empty());
    }

    /// Regression for #545 (read half): a recorded provider/model is restored
    /// when nothing else pinned the axis. Before the fix there was no such
    /// restore path, so the last choice was silently forgotten on restart.
    #[test]
    fn restore_applies_recorded_axes_when_unpinned() {
        let s = Session {
            provider: Some("dgx1".into()),
            model: Some("gpt-4.1".into()),
            model_from_project: false,
        };
        let r = s.restore(None, false, |n| n == "dgx1");
        assert_eq!(r.provider.as_deref(), Some("dgx1"));
        assert_eq!(r.model.as_deref(), Some("gpt-4.1"));
    }

    /// Regression for #545 (second reported case): a bare `/model` choice with
    /// no recorded provider sticks on the default-resolved backend.
    #[test]
    fn restore_applies_a_bare_model_on_the_default_backend() {
        let s = Session {
            provider: None,
            model: Some("gpt-4.1".into()),
            model_from_project: false,
        };
        let r = s.restore(None, false, |_| false);
        assert_eq!(r.provider, None);
        assert_eq!(r.model.as_deref(), Some("gpt-4.1"));
    }

    #[test]
    fn restore_yields_to_an_explicit_pin() {
        let s = Session {
            provider: Some("dgx1".into()),
            model: Some("gpt-4.1".into()),
            model_from_project: false,
        };
        // Provider pinned (to the SAME backend) + model pinned → both untouched.
        assert_eq!(s.restore(Some("dgx1"), true, |_| true), Restore::default());
        // Provider pinned to the same backend, model unpinned → model restores.
        let r = s.restore(Some("dgx1"), false, |_| true);
        assert_eq!(r.provider, None);
        assert_eq!(r.model.as_deref(), Some("gpt-4.1"));
    }

    /// Regression for the cross-provider model bleed: a model chosen for one
    /// backend must NOT be re-applied to a different backend that env or a
    /// `--loadout` pinned this run.
    #[test]
    fn restore_does_not_bleed_model_onto_a_different_pinned_provider() {
        let s = Session {
            provider: Some("openai".into()),
            model: Some("gpt-4.1".into()),
            model_from_project: false,
        };
        // A --loadout/env pinned dgx1; the openai-era model must not ride along.
        let r = s.restore(Some("dgx1"), false, |_| true);
        assert_eq!(r.provider, None);
        assert_eq!(r.model, None);
    }

    #[test]
    fn restore_drops_both_axes_when_the_provider_no_longer_exists() {
        let s = Session {
            provider: Some("ghost".into()),
            model: Some("gpt-4.1".into()),
            model_from_project: false,
        };
        // Unknown backend → provider dropped; the model belonged to that gone
        // backend, so it is dropped too rather than bleeding onto the default.
        let r = s.restore(None, false, |_| false);
        assert_eq!(r, Restore::default());
    }

    /// Regression for the ephemeral "leave no trace" invariant: switches in an
    /// ephemeral session must not be persisted.
    #[test]
    fn ephemeral_sessions_do_not_persist() {
        assert!(!should_persist(true));
        assert!(should_persist(false));
    }

    #[test]
    fn apply_sets_and_round_trips_through_text() {
        let mut d = toml::Table::new();
        apply_session_key(&mut d, "provider", Some("dgx1"));
        apply_session_key(&mut d, "model", Some("gpt-4.1"));
        let text = to_toml_string(&d).unwrap();
        assert!(text.starts_with("# newt — sticky user preferences"));
        let back = Session::from_doc(&doc(&text));
        assert_eq!(back.provider.as_deref(), Some("dgx1"));
        assert_eq!(back.model.as_deref(), Some("gpt-4.1"));
    }

    /// Regression for #545 (write half): `/backends` clears the model override.
    #[test]
    fn provider_switch_clears_the_model() {
        let mut d = doc("[session]\nprovider = \"openai\"\nmodel = \"gpt-4.1\"\n");
        apply_session_key(&mut d, "provider", Some("dgx1"));
        apply_session_key(&mut d, "model", None);
        let s = Session::from_doc(&d);
        assert_eq!(s.provider.as_deref(), Some("dgx1"));
        assert_eq!(s.model, None);
    }

    /// Hand-edit safety: an in-app rewrite preserves unknown keys/tables.
    #[test]
    fn rewrite_preserves_unknown_content() {
        let mut d =
            doc("top_pref = true\n\n[session]\nmodel = \"a\"\n\n[mine]\nnote = \"keep me\"\n");
        // Simulate `/backends dgx1`: set provider, clear model.
        apply_session_key(&mut d, "provider", Some("dgx1"));
        apply_session_key(&mut d, "model", None);
        let text = to_toml_string(&d).unwrap();
        // Serializes without a ValueAfterTable error and keeps the foreign bits.
        let back = doc(&text);
        assert_eq!(
            back.get("top_pref").and_then(toml::Value::as_bool),
            Some(true)
        );
        assert_eq!(
            back.get("mine")
                .and_then(toml::Value::as_table)
                .and_then(|t| t.get("note"))
                .and_then(toml::Value::as_str),
            Some("keep me")
        );
        assert_eq!(Session::from_doc(&back).provider.as_deref(), Some("dgx1"));
    }

    #[test]
    fn clearing_the_last_session_key_drops_the_empty_table() {
        let mut d = doc("[session]\nmodel = \"a\"\n");
        apply_session_key(&mut d, "model", None);
        assert!(!d.contains_key("session"));
    }

    // ---- per-project sticky choice (dec4) — pure, in-memory ----------------

    fn all_exist(_: &str) -> bool {
        true
    }

    fn switch(d: &mut toml::Table, proj: &str, c: Choice<'_>) {
        apply_project_choice(d, proj, c, Some("dflt"), all_exist);
    }

    /// (a)+(b): a switch in A leaves B on the global choice; A restores its own.
    #[test]
    fn a_switch_in_one_project_does_not_move_another() {
        let mut d = doc("[session]\nprovider = \"g\"\n");
        switch(&mut d, "/a", Choice::Provider("y"));
        assert_eq!(
            Session::for_project(&d, "/a").provider.as_deref(),
            Some("y")
        );
        assert_eq!(
            Session::for_project(&d, "/b").provider.as_deref(),
            Some("g")
        );
        // The global table is never written by a switch.
        assert_eq!(Session::from_doc(&d).provider.as_deref(), Some("g"));
    }

    /// (c): switching back to the global/default choice removes the entry.
    #[test]
    fn switching_back_removes_the_entry() {
        let mut d = doc("[session]\nprovider = \"g\"\n");
        switch(&mut d, "/a", Choice::Provider("y"));
        switch(&mut d, "/a", Choice::Provider("g"));
        assert!(!d.contains_key("projects"));
        // With no global provider the baseline is the config default.
        let mut d = doc("");
        switch(&mut d, "/a", Choice::Provider("y"));
        switch(&mut d, "/a", Choice::Provider("dflt"));
        assert!(!d.contains_key("projects"));
    }

    /// A model pick is kept per project and a provider switch clears it.
    #[test]
    fn model_is_per_project_and_a_provider_switch_clears_it() {
        let mut d = doc("[session]\nprovider = \"g\"\nmodel = \"gm\"\n");
        switch(&mut d, "/a", Choice::Model("m1"));
        let s = Session::for_project(&d, "/a");
        assert_eq!(
            (s.provider.as_deref(), s.model.as_deref()),
            (Some("g"), Some("m1"))
        );
        switch(&mut d, "/a", Choice::Provider("y"));
        let s = Session::for_project(&d, "/a");
        assert_eq!(
            (s.provider.as_deref(), s.model.as_deref()),
            (Some("y"), None)
        );
    }

    /// (d): 33 projects leave 32, and the least recently switched one is gone.
    #[test]
    fn the_table_is_capped_and_evicts_the_lru() {
        let mut d = doc("");
        for i in 0..=MAX_PROJECTS {
            switch(&mut d, &format!("/p{i}"), Choice::Provider("y"));
        }
        let t = d["projects"].as_table().expect("projects table");
        assert_eq!(t.len(), MAX_PROJECTS);
        assert!(!t.contains_key("/p0"), "the oldest entry is evicted");
        assert!(t.contains_key(&format!("/p{MAX_PROJECTS}")));
    }

    /// Recency, not insertion order: re-using an old project protects it.
    #[test]
    fn a_reused_project_is_not_the_lru() {
        let mut d = doc("");
        for i in 0..MAX_PROJECTS {
            switch(&mut d, &format!("/p{i}"), Choice::Provider("y"));
        }
        switch(&mut d, "/p0", Choice::Provider("z"));
        switch(&mut d, "/new", Choice::Provider("y"));
        let t = d["projects"].as_table().expect("projects table");
        assert!(t.contains_key("/p0") && !t.contains_key("/p1"));
    }

    /// (e): a path that no longer exists is pruned on the next write.
    #[test]
    fn a_deleted_path_is_pruned_on_the_next_write() {
        let mut d = doc("");
        switch(&mut d, "/gone", Choice::Provider("y"));
        apply_project_choice(&mut d, "/here", Choice::Provider("y"), Some("dflt"), |p| {
            p != "/gone"
        });
        let t = d["projects"].as_table().expect("projects table");
        assert!(!t.contains_key("/gone") && t.contains_key("/here"));
    }

    /// (f): ephemeral sessions write nothing (the gate the callers use).
    #[test]
    fn ephemeral_writes_nothing() {
        assert!(!should_persist(true));
    }

    /// #2622 EVIDENCE: a project-scoped model (written with no `provider`
    /// key, since it was picked while already on the project's active
    /// backend) restores even when the GLOBAL `[session]` provider has since
    /// gone stale and no longer names the backend actually in use — it must
    /// not be dropped just because the inherited `self.provider` disagrees
    /// with `effective`.
    #[test]
    fn a_project_scoped_model_restores_despite_a_stale_global_provider() {
        let mut d = doc("[session]\nprovider = \"ollama\"\n");
        switch(&mut d, "/a", Choice::Model("ornith-1.5-35b"));
        let s = Session::for_project(&d, "/a");
        assert_eq!(s.model.as_deref(), Some("ornith-1.5-35b"));
        // The active backend ("llama-router") does not match the stale
        // global "ollama" — the OLD guard dropped the model here.
        let r = s.restore(Some("llama-router"), false, all_exist);
        assert_eq!(
            r.model.as_deref(),
            Some("ornith-1.5-35b"),
            "a project's own remembered model must not be gated on a stale \
             global provider"
        );
    }

    /// PR #2626 review P1-2: a project entry that names ITS OWN provider
    /// couples model to that provider, same as a global entry — it is not
    /// the bare "picked while already active" case `model_from_project`
    /// exists for. An explicit-provider entry for a DIFFERENT backend than
    /// the one actually effective must not restore its model onto the
    /// wrong backend's credentials.
    #[test]
    fn explicit_project_provider_still_gates_the_model_on_a_mismatch() {
        let mut d = doc("");
        switch(&mut d, "/a", Choice::Provider("A"));
        switch(&mut d, "/a", Choice::Model("A-model"));
        let s = Session::for_project(&d, "/a");
        assert_eq!(
            (s.provider.as_deref(), s.model.as_deref()),
            (Some("A"), Some("A-model"))
        );
        // The effective backend is B (e.g. --loadout), not the project's A.
        let r = s.restore(Some("B"), false, all_exist);
        assert_eq!(
            r.model, None,
            "a model coupled to an explicit project provider must not \
             follow onto a different active backend"
        );
    }

    /// (g): the restore is lowest precedence — an env/flag-pinned provider is
    /// left alone even when the project has its own entry.
    #[test]
    fn a_pinned_provider_beats_the_project_entry() {
        let mut d = doc("");
        switch(&mut d, "/a", Choice::Provider("y"));
        let r = Session::for_project(&d, "/a").restore(Some("flag"), false, |_| true);
        assert_eq!(r.provider, None);
    }

    /// Unknown content and the header survive a project write.
    #[test]
    fn project_write_preserves_unknown_content() {
        let mut d = doc("[custom]\nk = 1\n");
        switch(&mut d, "/a", Choice::Provider("y"));
        assert!(d.contains_key("custom"));
        assert!(to_toml_string(&d).expect("ser").contains("PER PROJECT"));
    }

    /// The root is the nearest ancestor holding `.git` (dir or worktree file),
    /// else the cwd itself.
    #[test]
    fn root_is_the_git_ancestor_else_cwd() {
        let repo = Path::new("/r");
        let has_git = |p: &Path| p == repo.join(".git");
        assert_eq!(root_for(Path::new("/r/a/b"), has_git), repo);
        assert_eq!(root_for(Path::new("/r"), has_git), repo);
        assert_eq!(root_for(Path::new("/x/y"), |_| false), Path::new("/x/y"));
    }

    /// PR #2578 review: `newt headless --cwd A` launched from inside B keys on
    /// A, never on the process cwd B.
    #[test]
    fn the_workspace_beats_the_process_cwd() {
        let has_git = |p: &Path| p == Path::new("/a/.git") || p == Path::new("/b/.git");
        assert_eq!(
            key_for(Some(Path::new("/a/sub")), Path::new("/b"), has_git),
            Path::new("/a")
        );
        assert_eq!(key_for(None, Path::new("/b"), has_git), Path::new("/b"));
        let mut d = doc("");
        switch(&mut d, "/b", Choice::Provider("y"));
        assert_eq!(Session::for_project(&d, "/a").provider, None);
    }
}