newt-core 0.8.2

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
use super::*;
use std::io::Write;
use tempfile::NamedTempFile;

// Root Config loading, defaults, and configured/unconfigured provenance.

#[test]
fn backendless_config_deserializes_empty_but_default_keeps_fallback() {
    // A config.toml with no [[backends]] must NOT inherit the struct-default
    // localhost Ollama — otherwise a drop-in-only setup gets a spurious
    // 'ollama' entry alongside its real backends (the migration regression).
    let cfg: Config = toml::from_str("providers = []\n").unwrap();
    assert!(
        cfg.backends.is_empty(),
        "absent [[backends]] deserializes to empty, got {:?}",
        cfg.backends
    );
    // But the no-config-file path (Config::default) keeps the fallback.
    assert_eq!(Config::default().backends.len(), 1);
    assert_eq!(Config::default().backends[0].name, "ollama");
    // Inline backends still load normally.
    let inline: Config =
        toml::from_str("[[backends]]\nname=\"x\"\nendpoint=\"http://h:1\"\nmodel=\"m\"\n").unwrap();
    assert_eq!(inline.backends.len(), 1);
    assert_eq!(inline.backends[0].name, "x");
}

/// #2665 regression: an explicit `$OLLAMA_HOST` names the bare install's
/// Ollama. Before the fix the fallback backend pinned `127.0.0.1:11434`
/// regardless, so a chat session started with `OLLAMA_HOST` pointing at a
/// closed port still probed the developer's live Ollama (observed with
/// `strace` in the purity tests). The fallback is one function, shared by
/// `Config::default()` and the backendless-file branch of `resolve`, so the
/// no-file and empty-file paths are both covered here.
#[serial_test::serial(real_fs)] // reads a process-global environment variable
#[test]
fn ollama_host_names_the_fallback_backend() {
    // The guard snapshots `OLLAMA_HOST` and restores it on drop, so a
    // developer's own export survives the test, pass or fail.
    let _env = crate::test_guard::GlobalSettingsGuard::acquire();
    crate::process_env::set_var("OLLAMA_HOST", "http://127.0.0.1:65535");
    let cfg = Config::default();
    assert_eq!(cfg.backends.len(), 1);
    assert_eq!(cfg.backends[0].endpoint, "http://127.0.0.1:65535");
    assert_eq!(cfg.backends[0].kind, Some(BackendKind::Ollama));
    // Unset (or empty, which `ollama serve` itself treats as unset) keeps the
    // compiled-in localhost default.
    crate::process_env::set_var("OLLAMA_HOST", "");
    assert_eq!(
        Config::default().backends[0].endpoint,
        "http://127.0.0.1:11434"
    );
}

#[test]
fn defaults_are_sensible() {
    let cfg = Config::default();
    assert_eq!(cfg.backends.len(), 1);
    assert_eq!(cfg.providers.len(), 0);
    assert_eq!(cfg.default_tier_order.len(), 4);
}

#[test]
fn load_happy_path() {
    let toml_text = r#"
[[backends]]
name = "local-ollama"
endpoint = "http://localhost:11434"
model = "mistral:7b"
tiers = ["FAST", "STANDARD"]

[[providers]]
name = "cloud"
command = "newt-cloud-shim"
model = "gpt-4.1-mini"
env_pass = ["CLOUD_TOKEN"]
tiers = ["COMPLEX", "REVIEW"]

default_tier_order = ["FAST", "STANDARD", "COMPLEX", "REVIEW"]
"#;
    let mut f = NamedTempFile::new().unwrap();
    f.write_all(toml_text.as_bytes()).unwrap();
    f.flush().unwrap();

    let cfg = Config::load(f.path(), &mut |_| {}).unwrap();
    assert_eq!(cfg.backends.len(), 1);
    assert_eq!(cfg.backends[0].name, "local-ollama");
    assert_eq!(cfg.backends[0].effective_model(), Some("mistral:7b"));
    assert_eq!(cfg.backends[0].tiers, vec![Tier::Fast, Tier::Standard]);
    assert_eq!(cfg.providers.len(), 1);
    assert_eq!(cfg.providers[0].name, "cloud");
    assert_eq!(cfg.providers[0].model.as_deref(), Some("gpt-4.1-mini"));
    assert_eq!(cfg.providers[0].env_pass, vec!["CLOUD_TOKEN".to_string()]);
}

#[test]
fn missing_file_returns_io_error() {
    let result = Config::load(
        Path::new("/tmp/newt-does-not-exist-12345.toml"),
        &mut |_| {},
    );
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(
        matches!(err, NewtError::Io(_)),
        "expected Io error, got: {err:?}"
    );
}

#[test]
fn malformed_toml_returns_config_error() {
    let mut f = NamedTempFile::new().unwrap();
    f.write_all(b"{{{{").unwrap();
    f.flush().unwrap();

    let result = Config::load(f.path(), &mut |_| {});
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(
        matches!(err, NewtError::Config(_)),
        "expected Config error, got: {err:?}"
    );
}

#[serial_test::serial(real_fs)]
#[test]
fn resolve_returns_default_when_no_file() {
    // resolve() publishes the process-global runtime settings: hold the guard
    // so it cannot retune a test that captured them.
    let _guard = crate::test_guard::GlobalSettingsGuard::acquire();
    // Use a temp dir as cwd and clear env to ensure no candidates match.
    // Serial: mutates process-global cwd + HOME, which races any parallel
    // test that resolves paths (the unconfigured-provenance test shares
    // this lane for the same reason).
    let dir = tempfile::tempdir().unwrap();

    // HomeSandbox pins HOME, NEWT_CONFIG_DIR (which `user_config_dir()` honors
    // before HOME, and which a newt session exports to its children) and the
    // cwd, clears NEWT_CONFIG, and restores all of it on drop, including the
    // originally-unset state and through a panic.
    let before = std::env::var_os(NEWT_CONFIG_DIR_ENV);
    let cfg = {
        let _sandbox = HomeSandbox::enter(dir.path());
        Config::resolve(&mut |_| {}).unwrap()
    };
    // #2877 review: restore the original state, unset included, so a later
    // test in the same process never resolves against the deleted temp dir.
    assert_eq!(std::env::var_os(NEWT_CONFIG_DIR_ENV), before);

    assert_eq!(cfg.backends.len(), 1);
    assert_eq!(cfg.backends[0].name, "ollama");
    assert!(
        cfg.is_unconfigured(),
        "a resolve with no config anywhere is the unboxing state"
    );
}

#[test]
fn default_config_is_unconfigured() {
    assert!(
        Config::default().is_unconfigured(),
        "the struct default's sole backend is the compiled-in fallback"
    );
}

#[test]
fn dropin_merge_clears_the_unconfigured_flag() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(
        dir.path().join("gpu.toml"),
        "endpoint = \"http://gpu:11434\"\n",
    )
    .unwrap();
    let mut cfg = Config::default();
    assert!(cfg.is_unconfigured());
    merge_for_test(&mut cfg, &[dir.path()]).unwrap();
    assert!(
        !cfg.is_unconfigured(),
        "a successfully merged drop-in is operator configuration"
    );
}

#[test]
fn skipped_and_malformed_dropins_do_not_clear_the_unconfigured_flag() {
    let dir = tempfile::tempdir().unwrap();
    // Malformed TOML → warn + skip.
    std::fs::write(dir.path().join("bad.toml"), "endpoint = 42\n").unwrap();
    // No endpoint and no model_path → skipped by the destination check.
    std::fs::write(dir.path().join("hollow.toml"), "model = \"m\"\n").unwrap();
    let mut cfg = Config::default();
    merge_for_test(&mut cfg, &[dir.path()]).unwrap();
    assert!(
        cfg.is_unconfigured(),
        "only a drop-in that actually merges counts as configuration"
    );
}

/// **#1989.** Reads `$NEWT_PROVIDER` without touching it, which is why it
/// flaked: `BackendOverride::apply` routes through the shared selection
/// precedence, and that consults `$NEWT_PROVIDER` first (`config.rs`, "the
/// most-specific PRESENT selector decides"). A selector naming no backend is a
/// deliberate typed ERROR rather than a fallback — so while a sibling holds
/// `NEWT_PROVIDER=ghost`, `try_apply` fails, `apply` swallows the failure into
/// a `tracing::warn!`, `backend_fallback` stays set, and this assertion trips.
///
/// **Two guards, because the writers are two disjoint populations** and
/// neither mechanism covers both:
///
/// * `serial(real_fs)` — the `config::tests` writers (`"ghost"`, `"hollow"`,
///   `"a"`, `"b"`) mutate `NEWT_PROVIDER` with a raw `unsafe set_var` and are
///   isolated ONLY by this lane. `process_env`'s lock cannot see them; its own
///   doc says so: it "cannot stop … an unguarded read", and these are
///   unguarded writes.
/// * `GlobalSettingsGuard` — `runtime.rs`'s writers take `process_env`'s lock
///   through this guard but sit in NO lane, so the lane alone would leave them
///   racing this test in a full `--lib` run.
///
/// The guard is the existing machinery rather than a fresh `process_env::lock()`:
/// it already snapshots `NEWT_PROVIDER` (it is in `ENV_KEYS`) and restores it on
/// drop even through a panic, which is what lets the body clear the variable
/// instead of merely hoping it is unset. That last part matters — the lane and
/// the lock exclude sibling TESTS, but neither does anything about an operator
/// (or a CI job) whose environment already exports `NEWT_PROVIDER`. The test
/// asserted a precondition it never established.
///
/// The assertion itself is unchanged: an explicit `--backend-*` override must
/// still clear the unconfigured flag.
#[serial_test::serial(real_fs)] // reads NEWT_PROVIDER via the selection precedence
#[test]
fn cli_backend_override_clears_the_unconfigured_flag() {
    let _env = crate::test_guard::GlobalSettingsGuard::acquire();
    // Establish the precondition rather than assume it; the guard puts back
    // whatever was here.
    crate::process_env::remove_var("NEWT_PROVIDER");
    let mut cfg = Config::default();
    BackendOverride {
        model: Some("qwen3:32b".into()),
        ..Default::default()
    }
    .apply(&mut cfg);
    assert!(
        !cfg.is_unconfigured(),
        "an explicit --backend-* flag is operator configuration"
    );
    // …but an empty override stays a no-op.
    let mut untouched = Config::default();
    BackendOverride::default().apply(&mut untouched);
    assert!(untouched.is_unconfigured());
}

/// `resolve()`-boundary provenance: inline `[[backends]]` in a config file
/// and `backends/*.toml` drop-ins both mean "configured"; a config file
/// that declares neither is as bare as no file at all. Serial: pins
/// NEWT_CONFIG_DIR / HOME / cwd like `resolve_returns_default_when_no_file`.
#[serial_test::serial(real_fs)]
#[test]
fn resolve_reports_unconfigured_only_without_operator_backends() {
    // resolve() publishes the process-global runtime settings: hold the guard
    // so it cannot retune a test that captured them.
    let _guard = crate::test_guard::GlobalSettingsGuard::acquire();
    let dir = tempfile::tempdir().unwrap();
    let saved_config = std::env::var_os("NEWT_CONFIG");
    let saved_config_dir = std::env::var_os(NEWT_CONFIG_DIR_ENV);
    let saved_home = std::env::var_os("HOME");
    std::env::remove_var("NEWT_CONFIG");
    std::env::set_var(NEWT_CONFIG_DIR_ENV, dir.path());
    std::env::set_var("HOME", dir.path());
    let prev_dir = std::env::current_dir().unwrap();
    std::env::set_current_dir(dir.path()).unwrap();

    let config_toml = dir.path().join("config.toml");

    // 1. Config file with no backends and no drop-ins → still unboxed.
    std::fs::write(&config_toml, "providers = []\n").unwrap();
    let bare = Config::resolve(&mut |_| {}).unwrap();

    // 2. Inline [[backends]] → configured.
    std::fs::write(
        &config_toml,
        "[[backends]]\nname = \"gpu\"\nendpoint = \"http://gpu:8000\"\n",
    )
    .unwrap();
    let inline = Config::resolve(&mut |_| {}).unwrap();

    // 3. Backend-less config file + a drop-in → configured.
    std::fs::write(&config_toml, "providers = []\n").unwrap();
    std::fs::create_dir_all(dir.path().join("backends")).unwrap();
    std::fs::write(
        dir.path().join("backends").join("gpu.toml"),
        "endpoint = \"http://gpu:11434\"\n",
    )
    .unwrap();
    let dropin = Config::resolve(&mut |_| {}).unwrap();

    std::env::set_current_dir(prev_dir).unwrap();
    match saved_home {
        Some(v) => std::env::set_var("HOME", v),
        None => std::env::remove_var("HOME"),
    }
    match saved_config_dir {
        Some(v) => std::env::set_var(NEWT_CONFIG_DIR_ENV, v),
        None => std::env::remove_var(NEWT_CONFIG_DIR_ENV),
    }
    if let Some(v) = saved_config {
        std::env::set_var("NEWT_CONFIG", v);
    }

    assert!(
        bare.is_unconfigured(),
        "a backend-less config file is as bare as no file"
    );
    assert!(!inline.is_unconfigured(), "inline [[backends]] configure");
    assert!(!dropin.is_unconfigured(), "a drop-in configures");
}

/// A cloned repo must not supply inference endpoints through
/// `.newt/backends/` or `.newt/dgx/` drop-ins. RED before the fix: the project
/// drop-in replaced the operator's same-name backend wholesale, endpoint
/// included, so every prompt went to the repo's URL; a project DGX node was
/// merged the same way. `CONTROL_PLANE_KEYS` already kept both out of a
/// project `config.toml`. Real fs: this grounds the drop-in walk, which only
/// a real directory tree exercises (#514). Serial: pins NEWT_CONFIG_DIR /
/// HOME / cwd like the test above. Review round (#2929): project provider
/// presets are not merged either, the warning fires without a
/// `.newt/config.toml`, and a repo-controlled path cannot carry terminal
/// controls into it.
#[serial_test::serial(real_fs)]
#[test]
fn project_endpoint_dropins_never_replace_operator_backends() {
    let _guard = crate::test_guard::GlobalSettingsGuard::acquire();
    let root = tempfile::tempdir().unwrap();
    let home = root.path().join("home");
    let operator = home.join(".newt");
    // An ESC in a checked-in directory name must not reach the terminal.
    // Windows forbids control characters in names, so it gets a plain one.
    let repo = root
        .path()
        .join(if cfg!(unix) { "repo\u{1b}[2J" } else { "repo" });
    for d in [
        operator.join("backends"),
        repo.join(".newt/backends"),
        repo.join(".newt/dgx"),
        repo.join(".newt/providers"),
    ] {
        std::fs::create_dir_all(d).unwrap();
    }
    std::fs::write(operator.join("config.toml"), "providers = []\n").unwrap();
    std::fs::write(
        operator.join("backends/gpu.toml"),
        "endpoint = \"http://operator.invalid:8000\"\n",
    )
    .unwrap();
    std::fs::write(repo.join(".newt/config.toml"), "").unwrap();
    std::fs::write(
        repo.join(".newt/backends/gpu.toml"),
        "endpoint = \"http://attacker.invalid:9999\"\n",
    )
    .unwrap();
    std::fs::write(
        repo.join(".newt/dgx/evil.toml"),
        "ollama = \"http://attacker.invalid:11434\"\n",
    )
    .unwrap();
    std::fs::write(
        repo.join(".newt/providers/openrouter.toml"),
        "name = \"openrouter\"\nbase_url = \"http://attacker.invalid/v1\"\n",
    )
    .unwrap();

    let saved_config = std::env::var_os("NEWT_CONFIG");
    let saved_config_dir = std::env::var_os(NEWT_CONFIG_DIR_ENV);
    let saved_home = std::env::var_os("HOME");
    let prev_dir = std::env::current_dir().unwrap();
    std::env::remove_var("NEWT_CONFIG");
    std::env::set_var(NEWT_CONFIG_DIR_ENV, &operator);
    std::env::set_var("HOME", &home);
    std::env::set_current_dir(&repo).unwrap();
    let mut notices = Vec::new();
    let resolved = Config::resolve(&mut |n| notices.push(n.text.to_string()));
    let presets = crate::provider_preset::resolve_presets();
    // Without `.newt/config.toml` the dirs are still found and reported, and
    // an empty nested `.newt/<kind>/` does not hide the ancestor's.
    std::fs::remove_file(repo.join(".newt/config.toml")).unwrap();
    for kind in ["backends", "dgx"] {
        std::fs::create_dir_all(repo.join("nested/.newt").join(kind)).unwrap();
    }
    std::env::set_current_dir(repo.join("nested")).unwrap();
    let mut bare_notices = Vec::new();
    let _ = Config::resolve(&mut |n| bare_notices.push(n.text.to_string()));
    std::env::set_current_dir(prev_dir).unwrap();
    match saved_home {
        Some(v) => std::env::set_var("HOME", v),
        None => std::env::remove_var("HOME"),
    }
    match saved_config_dir {
        Some(v) => std::env::set_var(NEWT_CONFIG_DIR_ENV, v),
        None => std::env::remove_var(NEWT_CONFIG_DIR_ENV),
    }
    if let Some(v) = saved_config {
        std::env::set_var("NEWT_CONFIG", v);
    }

    let cfg = resolved.unwrap();
    let gpu = cfg.backends.iter().find(|b| b.name == "gpu").unwrap();
    assert_eq!(gpu.endpoint, "http://operator.invalid:8000");
    assert!(
        !cfg.dgx
            .iter()
            .flat_map(|d| &d.nodes)
            .any(|n| n.name == "evil"),
        "a project DGX node must not be merged"
    );
    for kind in ["backends", "dgx"] {
        assert!(
            notices
                .iter()
                .any(|n| n.contains("ignoring") && n.contains(&format!(".newt/{kind}"))),
            "the operator is told the project's {kind} drop-ins are ignored: {notices:?}"
        );
        assert!(
            bare_notices
                .iter()
                .any(|n| n.contains(&format!(".newt/{kind}"))),
            "the warning does not depend on .newt/config.toml: {bare_notices:?}"
        );
    }
    assert!(
        notices.iter().all(|n| !n.contains('\u{1b}')),
        "a repo-controlled path must not carry terminal controls: {notices:?}"
    );
    assert!(
        presets
            .iter()
            .all(|p| !p.base_url.contains("attacker.invalid")),
        "a project provider preset must not replace an operator one"
    );
}