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

#[test]
fn lifecycle_unavailable_run_suggests_explicit_build_with_same_phase_and_dir() {
    for dir in [None, Some("nested project")] {
        let mut args = serde_json::json!({"phase": "check", "action": "run"});
        let mut expected = serde_json::json!({"phase": "check", "action": "build"});
        if let Some(dir) = dir {
            args["dir"] = dir.into();
            expected["dir"] = dir.into();
        }
        let original = "error: cargo not in this profile's carried userland";
        let (text, outcome) =
            lifecycle_run_result(&args, (original.into(), crate::ExecOutcome::Unavailable));
        assert_eq!(outcome, crate::ExecOutcome::Unavailable);
        assert!(text.starts_with(original), "{text}");
        let suggestion = text
            .lines()
            .find_map(|line| line.strip_prefix("Suggested lifecycle call: "))
            .expect("unavailable run should expose the explicit build request");
        assert_eq!(
            serde_json::from_str::<serde_json::Value>(suggestion).unwrap(),
            expected
        );
        assert!(text.contains("explicit approval"), "{text}");
        assert!(text.contains("network denied"), "{text}");
        assert!(text.contains("denials remain binding"), "{text}");
        assert!(
            !text.contains("no command ran"),
            "a prior compound-command stage may have run"
        );
    }
}

#[test]
fn lifecycle_run_coaching_preserves_denials_and_executed_outcomes() {
    for outcome in [
        crate::ExecOutcome::Denied,
        crate::ExecOutcome::Failed,
        crate::ExecOutcome::Passed,
    ] {
        let original = ("original tool result".to_string(), outcome);
        assert_eq!(
            lifecycle_run_result(&serde_json::json!({"phase":"check"}), original.clone()),
            original,
        );
    }
}

/// F11: `lifecycle action=run` (the default) times out on the same 60s wall
/// as `run_command`. The confined shell already appends the build-lane
/// suggestion at the END of a (possibly truncated) envelope — measured
/// (newt main a996fb9e) not to steer the model. Put the exact next call
/// FIRST, ahead of the partial output, not just at the end.
#[test]
fn lifecycle_timed_out_run_puts_build_call_first() {
    let args = serde_json::json!({"phase": "test"});
    let original = (
        "partial output\n(the command hit the 60s wall and was killed...)".to_string(),
        crate::ExecOutcome::TimedOut,
    );
    let (text, outcome) = lifecycle_run_result(&args, original.clone());
    assert_eq!(outcome, crate::ExecOutcome::TimedOut);
    let first_line = text.lines().next().expect("non-empty result");
    let suggestion = first_line
        .strip_prefix("Suggested lifecycle call: ")
        .expect("build call must be the first line of a timed-out run result");
    assert_eq!(
        serde_json::from_str::<serde_json::Value>(suggestion).unwrap(),
        serde_json::json!({"phase": "test", "action": "build"})
    );
    assert!(
        text.ends_with(&original.0),
        "original (partial) output must be preserved: {text}"
    );
}

/// F12 (verify-lane-steering round 2): a model that learned "use lifecycle
/// action=build" sends `phase="build"` instead — `build` is an action, not
/// a phase, so `Phase::from_key` rejects it and it fell into the generic
/// "unknown lifecycle phase" refusal with no pointer to the real call. The
/// refusal must carry the same `{"phase":...,"action":"build"}` suggestion
/// as the timed-out-run coaching (`lifecycle_run_result`) — one JSON source,
/// not a second copy of the shape.
#[tokio::test]
async fn lifecycle_phase_build_points_at_action_build() {
    let caveats = crate::caveats::Caveats::top();
    let args = serde_json::json!({ "phase": "build" });
    let out = execute_tool(
        "lifecycle",
        &args,
        ".",
        false,
        20,
        &caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
    )
    .await;
    assert!(
        out.starts_with("error: unknown lifecycle phase 'build'"),
        "{out}"
    );
    let suggestion = out
        .lines()
        .find_map(|line| line.strip_prefix("Suggested lifecycle call: "))
        .expect("must point at the real action=build call: {out}");
    assert_eq!(
        serde_json::from_str::<serde_json::Value>(suggestion).unwrap(),
        serde_json::json!({"phase": "test", "action": "build"})
    );
}

/// F19 (red first): measured in replay 2483-r7 — nine `lifecycle action=run`
/// calls died at the 60s wall before one `action=build` call passed. The
/// timeout note already named the exact next call (F11); the model kept
/// retrying `run` anyway. `escalated_after_timeout` is what labels the
/// ONE re-run this fix routes into the build lane instead — it must say
/// plainly that the call escalated and why, and must preserve whatever the
/// build-lane re-run actually returned (pass, fail, or a fresh refusal),
/// never silently fall back to the original timeout text.
#[test]
fn escalated_after_timeout_labels_the_reroute_and_preserves_the_build_result() {
    let wall = shell::dispatch_wall("pytest -k slow", Default::default()); // a non-build-tool program → the default wall
    for (build_result, outcome) in [
        ("  ✓ build check passed".to_string(), crate::ExecOutcome::Passed),
        (
            "capability denied: lifecycle action=build requires explicit confined build authority; no command ran".to_string(),
            crate::ExecOutcome::Denied,
        ),
    ] {
        let (text, out) = escalated_after_timeout((build_result.clone(), outcome), wall);
        assert_eq!(out, outcome, "the build lane's own outcome is preserved");
        assert!(
            text.contains("action=run") && text.contains(&format!("{}s wall", wall.as_secs())),
            "must say plainly it escalated and why, with the wall that applied: {text}"
        );
        assert!(
            text.ends_with(&build_result),
            "the build lane's real result must survive verbatim: {text}"
        );
    }
}

/// #2541 round 2 item 3, round 3 item 2: the escalation's decision, isolated
/// from formatting and table-tested — only a genuine `TimedOut` under the
/// DEFAULT `run_command` wall justifies spending the build lane's authority
/// on a second run. #2732 preserves the longer budget for classified builds;
/// those must not rerun after spending that budget.
#[test]
fn escalates_only_on_a_default_wall_timeout() {
    let _env = crate::process_env::lock();
    let default_wall = shell::dispatch_wall("pytest -k slow", Default::default());
    let build_wall = shell::LIFECYCLE_BUILD_TIMEOUT;
    assert_eq!(
        shell::dispatch_wall("cargo test", Default::default(),),
        build_wall,
        "#2732: a classified build retains its build budget"
    );
    assert_ne!(
        default_wall, build_wall,
        "fixture sanity: the two walls must differ for this table to mean anything"
    );
    for (outcome, wall, expected) in [
        (crate::ExecOutcome::TimedOut, default_wall, true),
        (crate::ExecOutcome::TimedOut, build_wall, false),
        (crate::ExecOutcome::Passed, default_wall, false),
        (crate::ExecOutcome::Failed, default_wall, false),
        (crate::ExecOutcome::Denied, default_wall, false),
        (crate::ExecOutcome::Unavailable, default_wall, false),
    ] {
        assert_eq!(
            escalates(outcome, wall),
            expected,
            "escalates({outcome:?}, {wall:?}) should be {expected}"
        );
    }
}

/// #2541 round 2 item 1 (red first), round 3 item 4: when the escalation
/// itself does not execute — `Denied` (including a frame-isolation refusal,
/// which `run_confined_build_lane` also classes `Denied`) or `Unavailable`
/// — the FIRST run's RAW result is the only record of which test hung, and
/// it was being silently dropped in favor of the escalation's bare refusal
/// text. It must survive, with the refusal appended — never lost — and
/// WITHOUT the "Suggested lifecycle call: action=build" prefix
/// `lifecycle_run_result`'s `TimedOut` arm would otherwise prepend: that is
/// the exact call this refusal just declined, so opening a refused
/// escalation by recommending it is wrong (round 3 item 4).
#[test]
fn a_refused_escalation_keeps_the_first_runs_evidence() {
    let wall = shell::dispatch_wall("pytest -k slow", Default::default());
    // #2541 follow-up (red first): the confined shell already appends its
    // OWN `shell::timed_out_note(wall)` suffix to a timed-out result — which
    // itself recommends `lifecycle action=build` — before this call ever
    // knew the escalation would be declined. A hand-written fixture that
    // never included that real suffix (the prior shape of this test) could
    // not catch a result that carries TWO recommendations: the shell's own
    // "use action=build" immediately followed by "declined, do not retry
    // it". Use the REAL suffix here so the test can.
    let first = (
        format!(
            "partial: test_foo hung{}",
            shell::timed_out_note(wall, Default::default(),)
        ),
        crate::ExecOutcome::TimedOut,
    );
    for (refusal, outcome) in [
        (
            "capability denied: lifecycle action=build requires explicit confined build authority; no command ran".to_string(),
            crate::ExecOutcome::Denied,
        ),
        (
            "Error: frame isolation: tool authority exceeds the frame's ceiling".to_string(),
            crate::ExecOutcome::Denied,
        ),
        (
            "error: build workspace: No such file or directory".to_string(),
            crate::ExecOutcome::Unavailable,
        ),
    ] {
        let (text, out) = escalation_result(first.clone(), (refusal.clone(), outcome), wall, Default::default(),);
        assert_eq!(out, outcome, "the refusal's own class is the final outcome");
        assert!(
            text.contains("partial: test_foo hung"),
            "the first run's evidence (which test hung) must survive: {text}"
        );
        assert!(
            text.contains(&refusal),
            "the escalation's refusal must still be visible: {text}"
        );
        assert!(
            !text.contains("Suggested lifecycle call:"),
            "a refused escalation must not recommend the exact call that was just \
             declined: {text}"
        );
        assert!(
            !text.contains("call the tool with"),
            "a result must carry ONE recommendation — the shell's own timed-out \
             suggestion to use action=build (which literally says 'call the tool \
             with') must not survive alongside the 'declined, do not retry' line: \
             {text}"
        );
        assert!(
            text.contains("declined") && text.contains("narrow the command"),
            "must say plainly that build authority was declined and to narrow the \
             command instead of retrying it: {text}"
        );
    }
}

/// #2541 round 2 item 1, executing arm: when the escalation DOES run (any
/// outcome but `Denied`/`Unavailable`), its own result already speaks for the
/// whole call — `first`'s partial timeout output is superseded, not
/// duplicated, exactly as before this round's fix.
#[test]
fn an_executed_escalation_supersedes_the_first_runs_partial_output() {
    let wall = shell::dispatch_wall("pytest -k slow", Default::default());
    let first = (
        "partial: test_foo hung\n(the command hit the 60s wall and was killed...)".to_string(),
        crate::ExecOutcome::TimedOut,
    );
    let build_result = "  ✓ build check passed".to_string();
    let (text, out) = escalation_result(
        first,
        (build_result.clone(), crate::ExecOutcome::Passed),
        wall,
        Default::default(),
    );
    assert_eq!(out, crate::ExecOutcome::Passed);
    assert!(
        !text.contains("test_foo hung"),
        "an executed escalation's own result supersedes the first run's partial output: {text}"
    );
    assert!(text.ends_with(&build_result), "{text}");
}

/// #2541 round 2 item 5, round 3 item 3 (red first): a build-authority prompt
/// that fires because `action=run` escalated must say so — otherwise the
/// operator sees a `lifecycle action=build` permission request out of a call
/// they read as `action=run` and has no idea why. The wall named in the
/// reason must be DERIVED, never a literal "60s".
#[test]
fn the_escalation_names_itself_in_the_permission_prompt() {
    let base = crate::confined_exec::workspace_confined_caveats(std::path::Path::new("/ws"));
    let direct = lifecycle_build_request("/ws", "cargo test --offline", &base, None);
    assert!(
        !direct.reason.to_lowercase().contains("escalat"),
        "a direct action=build call names no escalation: {}",
        direct.reason
    );
    let wall = shell::dispatch_wall("pytest -k slow", Default::default());
    let reason = format!(
        "lifecycle action=run hit the confined shell's {}s wall",
        wall.as_secs()
    );
    let escalated = lifecycle_build_request("/ws", "cargo test --offline", &base, Some(&reason));
    assert!(
        escalated.reason.contains("escalation")
            && escalated.reason.contains("action=run")
            && escalated
                .reason
                .contains(&format!("{}s wall", wall.as_secs())),
        "the prompt must name why a build-authority request appeared: {}",
        escalated.reason
    );
}

/// #894 regression for the concrete drift that motivated the registry: the
/// `lifecycle` tool (#891) is advertised + dispatched, so it MUST be a real
/// name — otherwise every legitimate `lifecycle` call is miscounted as a
/// hallucination (inflating the anti-loop counter). Before the registry it
/// was missing from `ALL_TOOL_NAMES`; the derivation makes that impossible.
#[test]
fn lifecycle_is_a_real_tool_name_not_a_hallucination() {
    assert!(
        ALL_TOOL_NAMES.contains(&"lifecycle"),
        "lifecycle must be a real tool name"
    );
    assert!(
        !is_hallucination("lifecycle", &serde_json::json!({"phase": "test"})),
        "a real lifecycle call must not be flagged as a hallucination"
    );
}

#[test]
fn lifecycle_definition_enum_matches_phase_vocabulary() {
    // The schema's phase enum is built from `Phase::ALL`, so it can never
    // drift from the vocabulary the executor parses with `Phase::from_key`.
    let def = lifecycle_tool_definition();
    assert_eq!(def["function"]["name"], "lifecycle");
    let enum_vals: Vec<&str> = def["function"]["parameters"]["properties"]["phase"]["enum"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v.as_str().unwrap())
        .collect();
    let vocab: Vec<&str> = crate::tooling::Phase::ALL
        .iter()
        .map(|p| p.as_str())
        .collect();
    assert_eq!(enum_vals, vocab);
}

#[test]
fn run_phase_aliases_route_to_lifecycle() {
    for a in ["run_phase", "run_lifecycle", "lifecycle_run"] {
        assert!(
            matches!(
                resolve_tool_alias(a),
                Some(AliasOutcome::Rewrite("lifecycle"))
            ),
            "{a} should rewrite to lifecycle"
        );
    }
    // The canonical name is NOT an alias — it dispatches directly.
    assert!(resolve_tool_alias("lifecycle").is_none());
}

#[tokio::test]
async fn lifecycle_unknown_phase_lists_valid_phases() {
    // An unknown phase returns before any fs/subprocess touch, so this is a
    // fully-mocked unit test.
    let caveats = crate::caveats::Caveats::top();
    let args = serde_json::json!({ "phase": "deploy" });
    let out = execute_tool(
        "lifecycle",
        &args,
        ".",
        false,
        20,
        &caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
    )
    .await;
    assert!(
        out.starts_with("error: unknown lifecycle phase 'deploy'"),
        "{out}"
    );
    assert!(out.contains("check"), "should name valid phases: {out}");
}

/// Regression: a model that learned `lifecycle` as a task-state reporter in
/// another harness calls it with `{event|status|state, message}` and no
/// `phase`. Before the fix it got `error: unknown lifecycle phase ''` plus a
/// list of build phases — a dead end that says nothing about where task
/// state actually lives. It must instead be coached to update_plan /
/// request_user_input / the final answer. Returns before any fs touch, so
/// this is a fully-mocked unit test.
#[tokio::test]
async fn lifecycle_task_state_args_are_coached_to_update_plan() {
    let caveats = crate::caveats::Caveats::top();
    for args in [
        serde_json::json!({ "event": "complete", "message": "done" }),
        serde_json::json!({ "status": "blocked" }),
        serde_json::json!({ "state": "in_progress" }),
    ] {
        let out = execute_tool(
            "lifecycle",
            &args,
            ".",
            false,
            20,
            &caveats,
            &mut NoMcp,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        )
        .await;
        assert!(out.starts_with("error:"), "{args}: {out}");
        assert!(
            !out.contains("unknown lifecycle phase"),
            "{args}: still the phase dead-end: {out}"
        );
        for tool in ["update_plan", "request_user_input"] {
            assert!(out.contains(tool), "{args}: should coach to {tool}: {out}");
        }
    }
}

/// #1972 red-first, reproduced against this repo's own real tree (no
/// tempfile): `crates/` carries no lifecycle markers of its own, but its
/// child `crates/newt-tuner/` has a real `Cargo.toml` — the same shape as
/// the reported bug's `agent-voice/Cargo.toml`, invisible to root-anchored
/// detection before this fix. `workspace` is relative to `cargo test`'s cwd
/// (this crate's own directory), so `../crates` is the repo's real
/// `crates/` dir. Closes the loop end to end: the nested project is named
/// (not silently dropped), the message is honest (not `error:`-prefixed),
/// and the no-op no longer ledgers as a claimable success.
#[tokio::test]
async fn lifecycle_root_empty_names_a_nested_project_instead_of_a_silent_noop() {
    let caveats = crate::caveats::Caveats::top();
    let args = serde_json::json!({ "phase": "test" });
    let out = execute_tool(
        "lifecycle",
        &args,
        "../crates",
        false,
        20,
        &caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
    )
    .await;

    assert!(
        out.starts_with("no command configured for lifecycle phase 'test'"),
        "{out}"
    );
    assert!(
        out.contains("newt-tuner"),
        "names the nested project: {out}"
    );
    assert!(out.contains("dir=\"<path>\""), "points at the fix: {out}");
    assert!(
        !out.starts_with("error:"),
        "an honest degrade is not a fake failure: {out}"
    );
    assert!(
        !tool_result_ok(&out),
        "a no-op must not ledger as a claimable success: {out}"
    );
}

/// Twin of the above: `dir` resolves detection AND execution against the
/// SAME real nested project directly — proving the resolve_exec_cwd reuse
/// (#1972 part 1). `action=list` keeps this subprocess-free; `ok=true`
/// confirms a genuinely resolved phase is unaffected by the no-op
/// classifier added for the case above.
#[tokio::test]
async fn lifecycle_dir_param_resolves_a_nested_project_directly() {
    let caveats = crate::caveats::Caveats::top();
    let args = serde_json::json!({ "phase": "test", "action": "list", "dir": "newt-tuner" });
    let out = execute_tool(
        "lifecycle",
        &args,
        "../crates",
        false,
        20,
        &caveats,
        &mut NoMcp,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
    )
    .await;

    assert_eq!(out, "lifecycle test → cargo test", "got: {out}");
    assert!(
        tool_result_ok(&out),
        "a genuinely resolved phase is still ok=true: {out}"
    );
}

#[test]
fn run_build_check_reports_pass_fail_and_spawn_error() {
    let ws = tempfile::TempDir::new().unwrap();
    let ws_str = ws.path().to_string_lossy();

    // build_check now runs CONFINED through `ConstrainedExecutor` (P4). On the
    // normative Linux+Landlock platform the trivial commands run under the
    // fence, so we assert the exact confined pass/fail. Off it, the outcome
    // depends on the platform's kernel backend — Windows AppContainer / macOS
    // Seatbelt may confine-and-run, or the spawn fails closed — and BOTH are
    // secure (the executor never runs the repo-controlled command unconfined).
    // So off Linux we assert only a well-formed outcome, never the specific
    // one; the strong confinement guarantee is proven by the real-resource
    // Landlock test (`tests/confined_exec_landlock.rs`).
    //
    // `kernel_fs_fence_available()` is used (not `cfg!() &&
    // agent_bridle::landlock_is_supported()`): that symbol is Linux-only, so
    // calling it under a runtime `cfg!()` fails to COMPILE off Linux.
    let passed = run_build_check(passing_build_check_cmd(), &ws_str, &crate::Scope::none());
    if crate::confined_exec::kernel_fs_fence_available() {
        // Under the DenyAll egress floor the trivial command runs confined via
        // the net guard — resolved as a sibling `newt-net-guard` in a dev/test
        // build, or by `newt __net-guard` self-exec in production. In a minimal
        // build layout where the guard binary is not present the spawn fails
        // CLOSED (a secure outcome), so accept either the confined pass or the
        // fail-closed refusal; assert the fail path only when the pass path ran.
        if passed == "  ✓ build check passed" {
            let failed = run_build_check(
                &failing_build_check_cmd("boom"),
                &ws_str,
                &crate::Scope::none(),
            );
            assert!(failed.contains("✗ build check failed"), "got: {failed}");
            assert!(failed.contains("boom"), "stderr excerpt shown: {failed}");
        } else {
            assert!(
                passed.contains("⚠ build check could not run"),
                "with the egress floor, build_check must confine-and-run or fail \
                     closed, got: {passed}"
            );
        }
    } else {
        assert!(
            passed == "  ✓ build check passed" || passed.contains("⚠ build check could not run"),
            "off Linux, build_check must confine-and-run or fail closed, got: {passed}"
        );
    }
    // A nonexistent workspace dir → the command can't even spawn/confine.
    let err = run_build_check(
        passing_build_check_cmd(),
        "/definitely/not/a/dir",
        &crate::Scope::none(),
    );
    assert!(err.contains("⚠ build check could not run"), "got: {err}");
}

#[test]
fn lifecycle_build_authority_is_explicit_and_does_not_widen_shell_grants() {
    let base = crate::confined_exec::workspace_confined_caveats(std::path::Path::new("/ws"));
    let request = lifecycle_build_request("/ws", "cargo test --offline", &base, None);
    assert_eq!(request.kind, DenialKind::Build);
    assert_eq!(request.target, "/ws");
    assert!(request.reason.contains("cargo test --offline"));
    assert!(request.reason.contains("network denied"));
    assert!(
        !request.reason.contains("escalation"),
        "a direct action=build call names no escalation: {}",
        request.reason
    );
    assert_eq!(
        crate::agentic::permissions::widen_caveats(&base, &[(request.kind, request.target)]),
        base
    );
    assert_eq!(
        lifecycle_tool_definition()["function"]["parameters"]["properties"]["action"]["enum"],
        serde_json::json!(["run", "list", "build"])
    );
}

#[test]
fn lifecycle_build_prompt_reports_existing_network_authority() {
    let mut build = crate::confined_exec::build_tool_caveats(std::path::Path::new("/ws"));
    build.net = crate::Scope::All;
    let request = lifecycle_build_request("/ws", "cargo test", &build, None);
    assert!(
        request
            .reason
            .contains("network allowed by the existing operator grant"),
        "{}",
        request.reason
    );
    assert!(
        !request.reason.contains("network denied"),
        "{}",
        request.reason
    );
    build.net = crate::Scope::only(["example.test".into()]);
    let request = lifecycle_build_request("/ws", "cargo test", &build, None);
    assert!(
        request
            .reason
            .contains("network limited to the existing operator grant"),
        "{}",
        request.reason
    );
}

/// F38: a lifecycle `run` whose resolved command starts with a build tool
/// (cargo/just/make) must route to the build lane directly, not the run lane.
/// The model's first instinct (`lifecycle check` with no action) should work
/// when the resolved command is `just check`.
#[test]
fn lifecycle_run_of_build_tool_routes_to_build_lane() {
    assert!(
        lifecycle_run_routes_to_build_lane("just check"),
        "just is a build tool"
    );
    assert!(
        lifecycle_run_routes_to_build_lane("cargo test --workspace"),
        "cargo is a build tool"
    );
    assert!(
        lifecycle_run_routes_to_build_lane("make test"),
        "make is a build tool"
    );
    assert!(
        !lifecycle_run_routes_to_build_lane("pytest -x"),
        "pytest is not a build tool"
    );
    assert!(
        !lifecycle_run_routes_to_build_lane("python -m pytest"),
        "python is not a build tool"
    );
    assert!(
        !lifecycle_run_routes_to_build_lane(""),
        "empty command is not a build tool"
    );
}

/// F38 part (c): a lifecycle run whose resolved command is NOT a build tool
/// stays unchanged — it still goes through the run lane with escalation.
#[test]
fn lifecycle_run_of_non_build_tool_does_not_route() {
    // Non-build-tool lifecycle phases (e.g. a python-based test, a custom
    // script) must not be silently promoted to the build lane.
    assert!(!lifecycle_run_routes_to_build_lane("ruff check ."));
    assert!(!lifecycle_run_routes_to_build_lane("black --check ."));
    assert!(!lifecycle_run_routes_to_build_lane("mypy src/"));
}

/// #2731: a recovery note must reach the terminal override as well as the
/// model result, even when the build output is trimmed.
#[test]
fn cold_cache_recovery_is_visible_to_model_and_operator() {
    #[derive(Default)]
    struct Display(String);
    impl crate::agentic::display::ToolPresentation for Display {
        fn preview(&mut self, _: &str, _: usize) {}
        fn document(&mut self, _: &str) {}
        fn override_result(&mut self, text: String) {
            self.0 = text;
        }
    }
    for trim in [
        None,
        OutputTrim::from_json(Some(&serde_json::json!({"mode":"head","n":1}))),
    ] {
        let mut display = Display::default();
        let out = crate::confined_exec::ConfinedOutput {
            success: false,
            code: Some(101),
            stdout: b"build header\n".to_vec(),
            stderr: b"error: cache missing\n".to_vec(),
            timed_out: false,
            sandbox_kind: agent_bridle::SandboxKind::None,
        };
        let note = "note: automatic locked fetch was declined by the operator";
        let (model, outcome) = render_confined_build_result(
            Ok(out),
            Some(note),
            trim,
            10,
            false,
            false,
            None,
            &mut display,
        );
        assert_eq!(model.matches(note).count(), 1);
        assert_eq!(outcome, crate::ExecOutcome::Failed);
        assert!(
            display.0.contains(note),
            "operator missed recovery: {}",
            display.0
        );
    }
}