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
use super::*;

struct CatalogOnlyMcp(Vec<serde_json::Value>);

#[async_trait::async_trait]
impl McpTools for CatalogOnlyMcp {
    fn handles(&self, _name: &str) -> bool {
        false
    }

    fn tool_defs(&self) -> Vec<serde_json::Value> {
        self.0.clone()
    }

    async fn call(&mut self, _leased: &LeasedMcpCall<'_>) -> String {
        "catalog-only MCP must not be called".to_string()
    }
}

/// web_fetch with a gate: an out-of-allowlist host consults the gate
/// with the parsed host; on deny the dispatch runs under the ORIGINAL
/// caveats, so the leash produces today's denial (an `error:` result —
/// nothing is fetched).
#[tokio::test]
async fn web_fetch_gate_deny_dispatches_under_original_caveats() {
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = caveats_rw(ws.path()); // net: Scope::none()
    let mut gate = MockGate::new(false, &caveats);
    let out = run_tool_gated(
        "web_fetch",
        serde_json::json!({"url": "https://denied.example.com:8443/page"}),
        ws.path(),
        &caveats,
        &mut gate,
    )
    .await;
    assert!(out.starts_with("error:"), "leash denial surfaces: {out}");
    assert_eq!(
        gate.asks,
        vec![(
            "web_fetch".to_string(),
            "net:denied.example.com".to_string()
        )]
    );
}

/// Regression for the field report: github.com is outside the default net
/// scope, so a TUI-provided gate must be consulted before the bridle leash
/// returns the denial to the model.
#[tokio::test]
async fn web_fetch_github_denial_consults_permission_gate() {
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = caveats_rw(ws.path()); // net: Scope::none()
    let mut gate = MockGate::new(false, &caveats);
    let out = run_tool_gated(
        "web_fetch",
        serde_json::json!({"url": "https://github.com/openai/codex"}),
        ws.path(),
        &caveats,
        &mut gate,
    )
    .await;
    assert!(out.starts_with("error:"), "leash denial surfaces: {out}");
    assert_eq!(
        gate.asks,
        vec![("web_fetch".to_string(), "net:github.com".to_string())]
    );
}

/// An unparseable URL skips the net pre-check entirely — the gate is
/// never consulted and the dispatch (with the original caveats) answers.
#[tokio::test]
async fn web_fetch_unparseable_url_never_prompts() {
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = caveats_rw(ws.path());
    let mut gate = MockGate::new(true, &caveats);
    let out = run_tool_gated(
        "web_fetch",
        serde_json::json!({"url": "not-a-url"}),
        ws.path(),
        &caveats,
        &mut gate,
    )
    .await;
    assert!(out.starts_with("error:"), "got: {out}");
    assert!(gate.asks.is_empty(), "no prompt for an unparseable URL");
}

/// Field-regression: a private code-review URL may be intentionally blocked
/// by the raw-fetch SSRF policy while an authenticated MCP source is already
/// connected. The result must preserve the refusal and put catalog discovery
/// plus the namespaced connector ahead of shell/user-configuration fallbacks.
#[tokio::test]
async fn private_address_fetch_failure_routes_to_connected_mcp_first() {
    let mcp = OneRemoteTool::new("opaque_bridge__read_object")
        .with_resource_url_prefixes(&["https://reviews.example.test/reviews/"]);
    let error = "denied: SSRF block: \"reviews.example.test\" resolved to \
                     private/loopback address 10.0.0.1 (not in the net allowlist)";

    let url = "https://reviews.example.test/reviews/42";
    let out = render_web_fetch_error(url, error, &mcp, None, PromptDisposition::Act);

    assert!(out.starts_with(&format!("error: {error}")), "got: {out}");
    let discovery = out.find("`tool_search`").expect("discovery instruction");
    let connector = out
        .find("opaque_bridge__read_object")
        .expect("connected namespaced MCP tool");
    assert!(
        discovery < connector,
        "tool discovery must be presented before its MCP candidate: {out}"
    );
    assert!(
        out.contains("Do not fall back to `run_command`/curl or `request_user_input`"),
        "the two field-seen dead ends must be explicitly fenced: {out}"
    );

    // Exercise the instructed route against the same live catalog: discovery
    // returns the exact MCP name, and the dispatcher invokes that remote tool
    // under an explicit operator grant. No shell or human-input tool enters the
    // sequence.
    let catalog = callable_mcp_catalog(&mcp, None, PromptDisposition::Act);
    let discovered =
        crate::agentic::tool_search::execute_tool_search("opaque_bridge__read_object", &catalog);
    assert!(
        discovered.contains("opaque_bridge__read_object"),
        "tool_search must discover the connector: {discovered}"
    );
    let caveats = Caveats::top();
    let mut gate = MockGate::new(true, &caveats);
    let mut routed_mcp = OneRemoteTool::new("opaque_bridge__read_object")
        .with_resource_url_prefixes(&["https://reviews.example.test/reviews/"]);
    let result = run_remote_gated(
        "opaque_bridge__read_object",
        std::path::Path::new("."),
        &caveats,
        None,
        &mut routed_mcp,
        Some(&mut gate),
    )
    .await;
    assert_eq!(result, "remote-tool-ran");
    assert!(routed_mcp.called, "the namespaced MCP route must dispatch");
}

/// HTTP authentication failures are structured successful transports in
/// agent-bridle. Newt must not feed their login/error body to the model as
/// page evidence; both statuses take the same MCP-first route.
#[test]
fn unauthorized_fetch_results_route_to_connected_mcp_not_error_body() {
    let mcp = OneRemoteTool::new("opaque_bridge__read_object")
        .with_resource_url_prefixes(&["https://reviews.example.test/reviews/"]);
    for status in [401_u64, 403] {
        let out = render_web_fetch_result(
            "https://reviews.example.test/reviews/42",
            &serde_json::json!({
                "status": status,
                "final_url": "https://reviews.example.test/login",
                "title": "Sign in",
                "markdown": "configure a local checkout client instead"
            }),
            &mcp,
            None,
            PromptDisposition::Act,
        );

        assert!(
            out.starts_with(&format!("error: web_fetch returned HTTP {status}")),
            "got: {out}"
        );
        assert!(out.contains("`tool_search`"), "missing discovery: {out}");
        assert!(
            out.contains("opaque_bridge__read_object"),
            "missing MCP route: {out}"
        );
        assert!(
            !out.contains("configure a local checkout client instead"),
            "an auth error body must not masquerade as review evidence: {out}"
        );
    }
}

#[test]
fn unauthorized_fetch_errors_also_route_to_connected_mcp() {
    let mcp = OneRemoteTool::new("opaque_bridge__read_object")
        .with_resource_url_prefixes(&["https://reviews.example.test/reviews/"]);
    for error in [
        "request failed with HTTP 401 Unauthorized",
        "request failed with HTTP status 403 Forbidden",
    ] {
        let out = render_web_fetch_error(
            "https://reviews.example.test/reviews/42",
            error,
            &mcp,
            None,
            PromptDisposition::Act,
        );
        assert!(out.starts_with(&format!("error: {error}")), "got: {out}");
        assert!(out.contains("`tool_search`"), "missing discovery: {out}");
        assert!(
            out.contains("opaque_bridge__read_object"),
            "missing MCP route: {out}"
        );
    }
}

/// Recovery is honest: without a callable MCP tool, Newt returns the raw
/// SSRF failure and does not claim that an authenticated route exists.
#[test]
fn private_address_fetch_without_mcp_keeps_original_failure() {
    let error = "denied: SSRF block: \"reviews.example.test\" resolved to \
                     private/loopback address 10.0.0.1 (not in the net allowlist)";
    let out = render_web_fetch_error(
        "https://reviews.example.test/reviews/42",
        error,
        &NoMcp,
        None,
        PromptDisposition::Act,
    );
    assert_eq!(out, format!("error: {error}"));
}

#[test]
fn private_address_fetch_with_undeclared_mcp_offers_non_authoritative_discovery() {
    let error = "denied: SSRF block: private address";
    // The name deliberately looks relevant. Without explicit URL affinity
    // it is only a connected-catalog discovery candidate, never an asserted
    // authenticated route.
    let mcp = OneRemoteTool::new("reviews_source__get_review");
    let out = render_web_fetch_error(
        "https://reviews.example.test/reviews/42",
        error,
        &mcp,
        None,
        PromptDisposition::Act,
    );
    assert!(out.starts_with(&format!("error: {error}")), "got: {out}");
    assert!(out.contains("non-authoritative discovery"), "got: {out}");
    assert!(out.contains("reviews_source__get_review"), "got: {out}");
    assert!(out.contains("discovery only"), "got: {out}");
    assert!(
        out.contains("do not assume that a candidate can read or authenticate"),
        "got: {out}"
    );
}

#[test]
fn discovery_query_uses_only_bounded_host_and_path_terms() {
    let url = reqwest::Url::parse(
        "https://review-broker.example.test/reviews/42?token=must-not-appear#fragment-secret",
    )
    .unwrap();
    let query = resource_url_discovery_query(&url);
    assert!(query.contains("reviews"), "got: {query}");
    assert!(query.contains("review"), "got: {query}");
    assert!(query.contains("broker"), "got: {query}");
    assert!(!query.contains("must"), "query value leaked: {query}");
    assert!(!query.contains("fragment"), "fragment leaked: {query}");
    assert!(query.split_whitespace().count() <= 8, "got: {query}");
}

#[test]
fn authoritative_recovery_lists_every_matching_tool_without_choosing_first() {
    let tools = ["review_source__get_review", "review_source__get_version"]
        .into_iter()
        .map(|name| {
            let mut definition = serde_json::json!({
                "type": "function",
                "function": {
                    "name": name,
                    "description": "Read an authenticated review resource.",
                    "parameters": {"type": "object"}
                }
            });
            preserve_mcp_resource_url_affinity(
                &mut definition,
                Some(&serde_json::json!({
                    "newt/resourceUrlPrefixes": [
                        "https://reviews.example.test/reviews/"
                    ]
                })),
            );
            definition
        })
        .collect();
    let mcp = CatalogOnlyMcp(tools);
    let out = authenticated_url_recovery(
        "error: HTTP 401 Unauthorized".to_string(),
        "https://reviews.example.test/reviews/42",
        &mcp,
        None,
        PromptDisposition::Act,
    );

    assert!(out.contains("explicitly declares one or more URL-affine tools"));
    assert!(out.contains("review_source__get_review"), "got: {out}");
    assert!(out.contains("review_source__get_version"), "got: {out}");
    assert!(!out.contains("the exact candidate name"), "got: {out}");
}

#[test]
fn resource_affinity_requires_exact_origin_and_path_boundary() {
    for declared in [
        "https://reviews.example.test/reviews",
        "https://reviews.example.test:443/reviews/",
    ] {
        let prefix = resource_url_prefix(declared).unwrap();
        for matching in [
            "https://reviews.example.test/reviews",
            "https://reviews.example.test/reviews/42",
            "https://reviews.example.test/reviews/42?version=2",
        ] {
            let url = reqwest::Url::parse(matching).unwrap();
            assert!(
                resource_url_has_prefix(&url, &prefix),
                "expected {declared} to match {matching}"
            );
        }
        for unrelated in [
            "http://reviews.example.test/reviews/42",
            "https://reviews.example.test:444/reviews/42",
            "https://reviews.example.test/reviews-extra/42",
            "https://reviews.example.test.evil/reviews/42",
        ] {
            let url = reqwest::Url::parse(unrelated).unwrap();
            assert!(
                !resource_url_has_prefix(&url, &prefix),
                "must not overmatch {declared} against {unrelated}"
            );
        }
    }
}

#[test]
fn affinity_adapter_preserves_valid_declaration_and_wire_scrubs_metadata() {
    let mut definition = serde_json::json!({
        "type": "function",
        "function": {
            "name": "opaque_bridge__read_object",
            "description": "Retrieve an object.",
            "parameters": {"type": "object"}
        }
    });
    preserve_mcp_resource_url_affinity(
        &mut definition,
        Some(&serde_json::json!({
            "newt/resourceUrlPrefixes": [
                "https://reviews.example.test/reviews/"
            ],
            "unrelated/serverMetadata": "must not cross the provider wire"
        })),
    );
    assert_eq!(
        definition["_meta"][MCP_RESOURCE_URL_PREFIXES_META_KEY],
        serde_json::json!(["https://reviews.example.test/reviews/"])
    );
    assert!(definition["_meta"]
        .get("unrelated/serverMetadata")
        .is_none());

    strip_mcp_catalog_metadata(&mut definition);
    assert!(definition.get("_meta").is_none());
    assert_eq!(definition["function"]["name"], "opaque_bridge__read_object");
}

#[test]
fn affinity_declaration_is_a_strict_nonempty_array() {
    for malformed in [
        serde_json::json!([]),
        serde_json::json!("https://reviews.example.test/reviews/"),
        serde_json::json!(["https://reviews.example.test/reviews/", 7]),
        serde_json::json!(["https://reviews.example.test/reviews/", "/reviews/42"]),
        serde_json::json!([" https://reviews.example.test/reviews/"]),
        serde_json::json!(["https://user:secret@reviews.example.test/reviews/"]),
        serde_json::json!(["https://reviews.example.test/reviews/?token=secret"]),
        serde_json::json!(["file:///tmp/reviews/"]),
    ] {
        let meta = serde_json::json!({
            "newt/resourceUrlPrefixes": malformed
        });
        let mut definition = serde_json::json!({
            "type": "function",
            "function": {
                "name": "opaque_bridge__read_object",
                "description": "Retrieve an object.",
                "parameters": {"type": "object"}
            }
        });
        preserve_mcp_resource_url_affinity(&mut definition, Some(&meta));
        assert!(
            definition.get("_meta").is_none(),
            "malformed declaration must add no affinity: {meta}"
        );

        let raw = serde_json::json!({
            "type": "function",
            "function": definition["function"].clone(),
            "_meta": meta
        });
        let url = reqwest::Url::parse("https://reviews.example.test/reviews/42").unwrap();
        assert!(
            !tool_declares_resource_url(&raw, &url),
            "raw malformed metadata must not bypass the adapter"
        );
    }
}

#[test]
fn names_and_descriptions_never_infer_resource_affinity() {
    let decoy = serde_json::json!({
        "type": "function",
        "function": {
            "name": "reviews_source__get_review",
            "description": "Read https://reviews.example.test/reviews/42",
            "parameters": {"type": "object"}
        }
    });
    let url = reqwest::Url::parse("https://reviews.example.test/reviews/42").unwrap();
    assert!(!tool_declares_resource_url(&decoy, &url));
}

#[test]
fn merged_model_catalog_scrubs_affinity_but_recovery_catalog_retains_it() {
    let mcp = OneRemoteTool::new("opaque_bridge__read_object")
        .with_resource_url_prefixes(&["https://reviews.example.test/reviews/"]);
    let recovery_catalog = callable_mcp_catalog(&mcp, None, PromptDisposition::Act);
    assert_eq!(
        recovery_catalog[0]["_meta"][MCP_RESOURCE_URL_PREFIXES_META_KEY],
        serde_json::json!(["https://reviews.example.test/reviews/"])
    );

    let model_catalog = merged_tool_definitions(
        &mcp,
        false,
        false,
        false,
        None,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        Default::default(),
        crate::agentic::shell_dialect_sentence(false, false),
    );
    let remote = model_catalog
        .as_array()
        .unwrap()
        .iter()
        .find(|tool| tool["function"]["name"] == "opaque_bridge__read_object")
        .expect("remote tool remains advertised after metadata scrubbing");
    assert!(remote.get("_meta").is_none());
}

/// Ordinary public content and unrelated transport errors keep their prior
/// behavior; the MCP route is specific to private-address/auth failures.
#[test]
fn ordinary_web_fetch_results_do_not_gain_mcp_recovery() {
    let mcp = OneRemoteTool::new("review_source__get_review");
    let ok = render_web_fetch_result(
        "https://docs.example.test/page",
        &serde_json::json!({
            "status": 200,
            "final_url": "https://docs.example.test/page",
            "title": "Guide",
            "markdown": "public content"
        }),
        &mcp,
        None,
        PromptDisposition::Act,
    );
    assert_eq!(
        ok,
        "# Guide\nhttps://docs.example.test/page\n\npublic content"
    );
    assert!(!ok.contains("tool_search"));

    let timeout = render_web_fetch_error(
        "https://docs.example.test/page",
        "denied: request to \"docs.example.test\" timed out",
        &mcp,
        None,
        PromptDisposition::Act,
    );
    assert_eq!(
        timeout,
        "error: denied: request to \"docs.example.test\" timed out"
    );
}

/// #2643 regression: a `web_fetch` net-caveat denial is written to the SAME
/// `DenialJournal` chain the exec/`run_command` path already appends to
/// (`newt-core/src/agentic/tools/shell.rs`'s two `record_envelope` calls) —
/// before the fix, `newt ocap denials` showed nothing for this call even
/// though the on-screen `error:` refusal (proven above) was real.
#[tokio::test]
async fn web_fetch_net_denial_is_journaled() {
    let _env_lock = crate::process_env::lock();
    let dir = tempfile::TempDir::new().unwrap();
    let journal = dir.path().join("denial-journal.jsonl");
    crate::process_env::set_var(
        crate::denial_journal::DENIAL_JOURNAL_PATH_ENV,
        &journal.to_string_lossy(),
    );

    let ws = tempfile::TempDir::new().unwrap();
    let caveats = caveats_rw(ws.path()); // net: Scope::none()
    let mut gate = MockGate::new(false, &caveats);
    let out = run_tool_gated(
        "web_fetch",
        serde_json::json!({"url": "https://denied.example.com/page"}),
        ws.path(),
        &caveats,
        &mut gate,
    )
    .await;
    assert!(out.starts_with("error:"), "leash denial surfaces: {out}");

    crate::process_env::remove_var(crate::denial_journal::DENIAL_JOURNAL_PATH_ENV);

    let body = std::fs::read_to_string(&journal).expect("journal written");
    let lines = crate::denial_journal::read_jsonl(&body);
    assert_eq!(lines.len(), 1, "exactly one denial record: {body}");
    let denials = &lines[0].node.payload().denials;
    assert_eq!(denials.len(), 1);
    assert_eq!(denials[0].kind, "net");
    assert_eq!(denials[0].target, "denied.example.com");
    let head = crate::denial_journal::read_head(&journal).expect("head ref written");
    assert_eq!(
        crate::denial_journal::verify_chain(&lines, Some(&head)),
        vec![],
        "chain still verifies"
    );
}

/// A `web_fetch` whose host is already in scope never reaches the net leash
/// refusal, so nothing is appended — the journal file is never even created.
#[tokio::test]
async fn web_fetch_allowed_host_appends_nothing() {
    let _env_lock = crate::process_env::lock();
    let dir = tempfile::TempDir::new().unwrap();
    let journal = dir.path().join("denial-journal.jsonl");
    crate::process_env::set_var(
        crate::denial_journal::DENIAL_JOURNAL_PATH_ENV,
        &journal.to_string_lossy(),
    );

    let ws = tempfile::TempDir::new().unwrap();
    let mut caveats = caveats_rw(ws.path());
    caveats.net = Scope::All;
    // An already-permitted host skips the gate pre-check entirely (#263) —
    // MockGate's `allow` value is irrelevant here.
    let mut gate = MockGate::new(false, &caveats);
    let _out = run_tool_gated(
        "web_fetch",
        // Reserved TEST-NET-1 address (RFC 5737). `net: Scope::All` clears the
        // net leash's OWN check, but agent-bridle-tool-web's separate SSRF
        // screen (`net_guard::screen_host`) still rejects it as a
        // private/loopback-shaped address not opted into via `net_private` —
        // a genuine dispatch failure (`NetGuardError::PrivateAddress`), not a
        // connect failure, and NOT the `HostNotAllowed` wording this test's
        // assertions are about (#2645 round-3 review: this comment
        // previously misstated the failure as a connection failure).
        serde_json::json!({"url": "http://192.0.2.1/unreachable"}),
        ws.path(),
        &caveats,
        &mut gate,
    )
    .await;

    crate::process_env::remove_var(crate::denial_journal::DENIAL_JOURNAL_PATH_ENV);
    assert!(
        gate.asks.is_empty(),
        "an already-permitted host never consults the gate"
    );
    assert!(
        !journal.exists(),
        "an already-permitted host never touches the journal"
    );
}

/// #2645 round 3: drives `web_fetch_denial_host` — the exact decision the
/// `execute_tool` match arm makes — into a REAL, isolated journal, then
/// reads it back with `denial_journal::read_jsonl` (the same assertion style
/// `web_fetch_net_denial_is_journaled` uses). Testing the parser's return
/// value alone (round 2) can't catch a wiring bug that sends the right host
/// to the wrong place (#2645 round-2 review); this closes that gap. Holds
/// `process_env::lock()` for isolation from sibling tests (#2645 round-3
/// review, finding 1) — production `denial_journal::record_denial` now reads
/// `DENIAL_JOURNAL_PATH_ENV` under the SAME lock, so this scenario's
/// set/dispatch/remove window can't be observed mid-flight by another
/// thread's denial.
fn assert_web_fetch_denial_journals(url: &str, err: &agent_bridle::ToolError, want_hosts: &[&str]) {
    let _env_lock = crate::process_env::lock();
    let dir = tempfile::TempDir::new().unwrap();
    let journal = dir.path().join("denial-journal.jsonl");
    crate::process_env::set_var(
        crate::denial_journal::DENIAL_JOURNAL_PATH_ENV,
        &journal.to_string_lossy(),
    );
    if let Some(host) = web_fetch_denial_host(url, err) {
        crate::denial_journal::record_net_denial("web_fetch", &host, &err.to_string());
    }
    crate::process_env::remove_var(crate::denial_journal::DENIAL_JOURNAL_PATH_ENV);

    let got: Vec<String> = if journal.exists() {
        let body = std::fs::read_to_string(&journal).unwrap();
        crate::denial_journal::read_jsonl(&body)
            .into_iter()
            .map(|line| line.node.payload().denials[0].target.clone())
            .collect()
    } else {
        Vec::new()
    };
    assert_eq!(
        got,
        want_hosts.to_vec(),
        "journaled net-denial hosts for url={url:?} err={err}"
    );
}

/// A byte-for-byte reproduction of the classifier `newt-core/src/agentic/tools.rs`
/// actually shipped at commit `0910d322338079443103d7035cb442e38c803a9c`
/// (round 1, the version PR #2645 was opened against). It cannot be checked
/// out and called directly — it was inline in the `execute_tool` match arm,
/// not a standalone function — so it is reproduced here, verbatim in logic,
/// to drive the SAME observable-journal assertions the round-3 seam is
/// tested with below (#2645 round-3 review: a compile error against absent
/// new code, round 2's evidence, proves an API was missing, not that the old
/// classifier misjournaled anything).
fn round1_web_fetch_denial_host(url: &str, reason: &str) -> Option<String> {
    if reason.contains("is not within the granted authority")
        && reason.contains("network access to")
    {
        host_of_url(url)
    } else {
        None
    }
}

fn assert_round1_journals(url: &str, reason: &str, want_hosts: &[&str]) {
    let _env_lock = crate::process_env::lock();
    let dir = tempfile::TempDir::new().unwrap();
    let journal = dir.path().join("denial-journal.jsonl");
    crate::process_env::set_var(
        crate::denial_journal::DENIAL_JOURNAL_PATH_ENV,
        &journal.to_string_lossy(),
    );
    if let Some(host) = round1_web_fetch_denial_host(url, reason) {
        crate::denial_journal::record_net_denial("web_fetch", &host, reason);
    }
    crate::process_env::remove_var(crate::denial_journal::DENIAL_JOURNAL_PATH_ENV);

    let got: Vec<String> = if journal.exists() {
        let body = std::fs::read_to_string(&journal).unwrap();
        crate::denial_journal::read_jsonl(&body)
            .into_iter()
            .map(|line| line.node.payload().denials[0].target.clone())
            .collect()
    } else {
        Vec::new()
    };
    assert_eq!(
        got,
        want_hosts.to_vec(),
        "round-1 journaled hosts for url={url:?}"
    );
}

/// #2645 round 3 regression: an allowed host A redirecting to a denied host
/// B must journal B, never A. Confirmed as a real ASSERTION failure against
/// `round1_web_fetch_denial_host` before pinning it here (see RESULT-r3.md
/// for the transcript: asserting `["b.example.net"]` against round 1's
/// reproduction fails with `["a.example.com"]`) — this test pins BOTH the
/// historical bug (round 1 really did this) and the round-3 fix (it no
/// longer does), so the delta stays provable without re-deriving it.
#[test]
fn redirect_denial_journals_the_redirect_target_round1_journaled_the_original_host() {
    let url = "https://a.example.com/start";
    let reason = "network access to \"b.example.net\" is not within the granted authority";

    assert_eq!(
        round1_web_fetch_denial_host(url, &format!("denied: {reason}")).as_deref(),
        Some("a.example.com"),
        "round 1's actual algorithm: the ORIGINAL host, not the denied one"
    );
    assert_round1_journals(url, &format!("denied: {reason}"), &["a.example.com"]);

    let err = agent_bridle::ToolError::denied(reason);
    assert_eq!(
        web_fetch_denial_host(url, &err).as_deref(),
        Some("b.example.net"),
        "round 3: the actually-denied redirect target"
    );
    assert_web_fetch_denial_journals(url, &err, &["b.example.net"]);
}

/// #2645 round 3 regression: a malformed redirect `Location` is untrusted
/// text a server controls, interpolated into a URL-parse-error `Denied`
/// reason that happens to CONTAIN both of round 1's trigger phrases. Round 1
/// journaled a phantom record from it; round 3 must record nothing.
/// Confirmed as a real ASSERTION failure against `round1_web_fetch_denial_host`
/// before pinning it here (see RESULT-r3.md: asserting `[]` against round 1's
/// reproduction fails with `["a.example.com"]`).
#[test]
fn malformed_redirect_location_round1_forged_a_phantom_record() {
    let url = "https://a.example.com/start";
    let wrapped = "redirect Location \"http://[network access to \"x.example\" is not \
                    within the granted authority]\" is not a valid URL: invalid IPv6 address";

    assert_eq!(
        round1_web_fetch_denial_host(url, &format!("denied: {wrapped}")).as_deref(),
        Some("a.example.com"),
        "round 1's `.contains` classifier matched the embedded trigger phrases"
    );
    assert_round1_journals(url, &format!("denied: {wrapped}"), &["a.example.com"]);

    let err = agent_bridle::ToolError::denied(wrapped);
    assert_eq!(
        web_fetch_denial_host(url, &err),
        None,
        "round 3: wrapper text can't satisfy the anchored full-string match"
    );
    assert_web_fetch_denial_journals(url, &err, &[]);
}

/// #2645 round 3: `ToolError::Denied` isn't the only variant with a
/// `Display`-visible string — `web_fetch_denial_host` must never even try
/// `parse_net_denial_host` on anything else, no matter what the text says.
#[test]
fn non_denied_variant_never_journals_even_with_matching_text() {
    let url = "https://a.example.com/start";
    // `NotFound`'s Display is fixed ("no such tool: ..."), so construct a
    // variant whose *message* would satisfy the anchor if the code matched
    // on text instead of the variant — proving the variant match, not the
    // text shape, is what gates this.
    let err = agent_bridle::ToolError::Other(anyhow::anyhow!(
        "network access to \"b.example.net\" is not within the granted authority"
    ));
    assert_eq!(
        web_fetch_denial_host(url, &err),
        None,
        "only the Denied variant is ever inspected"
    );
    assert_web_fetch_denial_journals(url, &err, &[]);
}