lean-ctx-server 3.12.11

The LeanCTX MCP server and its tools on top of LeanCTX | OSS.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
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
// SPDX-License-Identifier: Apache-2.0
use super::{
    CtxShellTool, collect_extra_env, detect_heredoc_reroute, format_background_snapshot,
    is_timeout_notice_only, resolve_effective_cwd, shell_access_denial, should_auto_background,
};
use crate::server::background_shell::JobState;
use crate::server::tool_trait::{
    BackgroundJobState, BackgroundShellOutcome, McpTool, ShellOutcome, ToolContext,
};
use serde_json::{Map, Value};

fn env_args(pairs: &[(&str, &str)]) -> Map<String, Value> {
    let mut env = Map::new();
    for (key, value) in pairs {
        env.insert((*key).to_string(), Value::String((*value).to_string()));
    }
    let mut args = Map::new();
    args.insert("env".to_string(), Value::Object(env));
    args
}

/// #1771: the inline-override refusal points callers at `env` and uses `PATH`
/// as its example, so silently dropping `PATH` here made the recommended
/// recovery run with the inherited value and report success.
#[test]
fn env_refuses_protected_key_by_name_instead_of_dropping_it() {
    let args = env_args(&[("PATH", "/tmp/evil"), ("RUST_LOG", "debug")]);
    let error = collect_extra_env(&args).expect_err("PATH must be refused, not dropped");
    assert!(
        error.contains("`PATH`"),
        "the refusal must name the offending key, got: {error}"
    );
    assert!(
        error.contains("nothing was run"),
        "the caller must learn the command did not run, got: {error}"
    );
}

#[test]
fn env_refusal_names_every_rejected_key_in_sorted_order() {
    let args = env_args(&[("PATH", "/x"), ("LD_PRELOAD", "/y")]);
    let error = collect_extra_env(&args).expect_err("both keys are protected");
    let ld = error.find("LD_PRELOAD").expect("LD_PRELOAD must be named");
    let path = error.find("`PATH`").expect("PATH must be named");
    assert!(ld < path, "keys must be listed sorted, got: {error}");
}

#[test]
fn env_passes_ordinary_keys_through() {
    let args = env_args(&[("RUST_LOG", "debug")]);
    let accepted = collect_extra_env(&args).expect("ordinary keys are allowed");
    assert_eq!(accepted.get("RUST_LOG").map(String::as_str), Some("debug"));
}

#[test]
fn env_absent_is_not_an_error() {
    let args = Map::new();
    assert!(
        collect_extra_env(&args)
            .expect("a missing env object is fine")
            .is_empty()
    );
}

fn background(outcome: ShellOutcome) -> BackgroundShellOutcome {
    let ShellOutcome::Background(outcome) = outcome else {
        panic!("expected a background outcome");
    };
    outcome
}

fn format_snapshot_state(
    id: &str,
    is_cancel: bool,
    state: Option<JobState>,
) -> (String, ShellOutcome) {
    format_noticed_snapshot(id, is_cancel, state, None)
}

fn format_noticed_snapshot(
    id: &str,
    is_cancel: bool,
    state: Option<JobState>,
    notice: Option<&'static str>,
) -> (String, ShellOutcome) {
    let snapshot = state.map(|state| {
        let actual_exit_code = match &state {
            JobState::Running { .. } => 0,
            JobState::Completed { exit_code, .. } => *exit_code,
            JobState::Cancelled { .. } => 130,
        };
        let output_withheld = !matches!(&state, JobState::Running { .. });
        crate::server::background_shell::JobSnapshot {
            state,
            generation: 1,
            completeness: lean_ctx::core::context_admission::OutputCompleteness::complete(),
            // This fixture exercises the safe withheld-output path without
            // inserting or retaining a synthetic job in the global registry.
            output_withheld,
            actual_exit_code,
            notice,
            class: lean_ctx::core::context_admission::origin::SourceClass::Project,
        }
    });
    format_background_snapshot(id, is_cancel, snapshot)
}

/// Q13: a finished job's notice is the first line of what a status poll or a
/// cancel shows, once: in the header, which is put in front of the reply
/// after the text was archived and shortened — never in that text. A job
/// without a notice is rendered exactly as before.
#[test]
fn a_finished_jobs_notice_leads_the_header_and_is_not_in_the_text() {
    const NOTICE: &str = "[lean-ctx: a fixed notice]";
    let finished = [
        JobState::Completed {
            output: "out".into(),
            exit_code: 3,
        },
        JobState::Cancelled {
            output: "out".into(),
        },
    ];
    for state in finished {
        for is_cancel in [false, true] {
            let (plain_text, plain) =
                format_snapshot_state("shell_x", is_cancel, Some(state.clone()));
            let (text, noticed) =
                format_noticed_snapshot("shell_x", is_cancel, Some(state.clone()), Some(NOTICE));
            assert_eq!(text, plain_text, "the text is the same with a notice");
            assert!(!text.contains(NOTICE));
            let (plain, mut noticed) = (background(plain), background(noticed));
            let plain_header = plain.display.as_ref().unwrap().header.clone();
            let header = noticed.display.as_ref().unwrap().header.clone();
            assert_eq!(header, format!("{NOTICE}\n{plain_header}"));
            assert_eq!(header.matches(NOTICE).count(), 1);
            // Nothing else of the outcome differs.
            noticed.display.as_mut().unwrap().header = plain_header;
            assert_eq!(noticed, plain);
        }
    }
}

/// #1246: a cancel must never come back as a tool error, and must not read
/// like a status poll that did nothing.
///
/// #1674: the second half of that only became true here. This asserted
/// `Running` — the very value that made a cancel indistinguishable from a
/// poll, against the intent stated one line above. #1246 fixed the
/// error-reporting half and left the state; the state is the half the
/// caller reads.
#[test]
fn cancel_is_acknowledged_and_never_reports_a_failure() {
    let running = JobState::Running {
        output: String::new(),
    };
    let (text, outcome) = format_snapshot_state("shell_x", true, Some(running.clone()));
    let outcome = background(outcome);
    assert!(!outcome.is_error);
    assert_eq!(outcome.state, BackgroundJobState::Cancelled);
    assert_eq!(outcome.exit_code, None);
    assert!(text.is_empty(), "{text:?}");
    assert!(
        outcome
            .display
            .as_ref()
            .is_some_and(|display| display.header.contains("cancel requested"))
    );

    // A status poll of the same state keeps the old wording.
    let (text, outcome) = format_snapshot_state("shell_x", false, Some(running));
    let outcome = background(outcome);
    assert!(!outcome.is_error);
    assert_eq!(outcome.state, BackgroundJobState::Running);
    assert_eq!(text, "[background:shell_x running]");
    assert!(
        outcome
            .display
            .as_ref()
            .is_some_and(|display| display.header == "[background:shell_x running]")
    );

    // The terminal child code is data; the requested cancel remains a
    // successful tool action even though structuredContent keeps 130.
    let (text, outcome) = format_snapshot_state(
        "shell_x",
        true,
        Some(JobState::Cancelled {
            output: "[cancelled: command stopped on request]".to_string(),
        }),
    );
    let outcome = background(outcome);
    assert!(!outcome.is_error);
    assert_eq!(outcome.state, BackgroundJobState::Cancelled);
    assert_eq!(outcome.exit_code, Some(130));
    assert!(text.contains("retained output withheld by storage policy"));
    assert!(
        outcome
            .display
            .as_ref()
            .and_then(|display| display.footer.as_deref())
            .is_some_and(|footer| footer == "[cancelled: shell_x, exit 130]")
    );

    // Idempotent: already finished, or finished and pruned.
    let finished = JobState::Completed {
        output: "boom".to_string(),
        exit_code: 1,
    };
    let cancelled_finished =
        background(format_snapshot_state("shell_x", true, Some(finished.clone())).1);
    assert!(!cancelled_finished.is_error);
    assert_eq!(cancelled_finished.state, BackgroundJobState::Failed);
    assert_eq!(cancelled_finished.exit_code, Some(1));

    let polled_finished = background(format_snapshot_state("shell_x", false, Some(finished)).1);
    assert!(polled_finished.is_error);
    assert_eq!(polled_finished.state, BackgroundJobState::Failed);
    assert_eq!(polled_finished.exit_code, Some(1));

    let missing_cancel = format_snapshot_state("shell_x", true, None).1;
    assert!(!missing_cancel.is_error());
    assert_eq!(missing_cancel, ShellOutcome::Exit(0));

    let missing_status = format_snapshot_state("shell_x", false, None).1;
    assert!(missing_status.is_error());
    assert!(matches!(
        missing_status,
        ShellOutcome::BackgroundLookupError(_)
    ));
}

#[test]
fn long_cargo_test_is_auto_backgrounded() {
    assert!(should_auto_background(
        "cargo test --lib a\ncargo test --lib b",
        Some(3_600_000)
    ));
    assert!(should_auto_background("cargo test --lib a", Some(300_000)));
    assert!(!should_auto_background("cargo test --lib a", Some(299_999)));
}

#[test]
fn timeout_notice_without_child_output_is_not_recoverable() {
    assert!(is_timeout_notice_only(
        "ERROR: command timed out after 200ms",
        124
    ));
    assert!(is_timeout_notice_only(
        "  ERROR: command timed out after 200ms\n",
        124
    ));
    assert!(!is_timeout_notice_only(
        "useful output\nERROR: command timed out after 200ms",
        124
    ));
    assert!(!is_timeout_notice_only(
        "ERROR: command timed out after 200ms",
        1
    ));
    // #1173: the notice now carries the idle wording and the still-running
    // segment list. It is still pure metadata — nothing to recover — so it
    // must not become a tee artifact just because it grew.
    assert!(is_timeout_notice_only(
        "ERROR: command timed out after 200ms without new output\n\
             [still running at timeout: sleep 300]",
        124
    ));
    assert!(!is_timeout_notice_only(
        "useful output\nERROR: command timed out after 200ms\n\
             [still running at timeout: sleep 300]",
        124
    ));
    // Exit 124 from something that is not our watchdog carries no marker.
    assert!(!is_timeout_notice_only("some tool output", 124));
}

#[test]
fn unavailable_session_lock_rejects_explicit_cwd() {
    let error = resolve_effective_cwd(None, Some("/tmp/unvalidated"))
        .expect_err("an unavailable session lock must reject an unvalidated cwd");
    assert!(
        error.message.contains("cannot validate working directory"),
        "{error:?}"
    );
}

#[test]
fn untrusted_and_readonly_clients_cannot_run_shell_commands() {
    for role in ["untrusted", "readonly"] {
        let ctx = ToolContext {
            client_role: Some(role.to_string()),
            ..ToolContext::default()
        };
        let output = CtxShellTool
            .handle(&serde_json::Map::new(), &ctx)
            .expect("role denial must be a tool result");

        assert_eq!(output.shell_outcome, Some(ShellOutcome::Blocked));
        assert!(
            output.text.contains("SHELL ACCESS DENIED"),
            "{role}: {}",
            output.text
        );
        assert!(output.text.contains(role), "{role}: {}", output.text);
    }
}

#[test]
fn absent_shell_context_preserves_default_access() {
    assert!(shell_access_denial(&ToolContext::default()).is_none());
}

#[test]
fn explicitly_disabled_shell_access_blocks_the_request() {
    let ctx = ToolContext {
        shell_access: Some(false),
        ..ToolContext::default()
    };
    let output = CtxShellTool
        .handle(&serde_json::Map::new(), &ctx)
        .expect("shell-access denial must be a tool result");

    assert_eq!(output.shell_outcome, Some(ShellOutcome::Blocked));
    assert!(output.text.contains("shell_access=true"), "{}", output.text);
}

#[test]
fn detect_heredoc_reroute_python_quoted() {
    let cmd = "python3 - <<'PY'\nprint(1)\nPY";
    let (lang, code, rest) = detect_heredoc_reroute(cmd).expect("must detect python heredoc");
    assert_eq!(lang, "python");
    assert_eq!(code, "print(1)");
    assert!(rest.is_none());
}

#[test]
fn detect_heredoc_reroute_python_with_remainder() {
    let cmd = "python3 <<'PY'\nprint(1)\nPY\nnode --test file.js";
    let (lang, code, rest) = detect_heredoc_reroute(cmd).expect("must detect split heredoc");
    assert_eq!(lang, "python");
    assert_eq!(code, "print(1)");
    assert_eq!(rest.as_deref(), Some("node --test file.js"));
}

#[test]
fn detect_heredoc_reroute_unquoted_and_tab_stripped() {
    let unquoted = "ruby <<EOF\nputs 1\nEOF";
    let (lang, code, rest) = detect_heredoc_reroute(unquoted).unwrap();
    assert_eq!(lang, "ruby");
    assert_eq!(code, "puts 1");
    assert!(rest.is_none());

    let tabbed = "python3 <<-\tSCRIPT\n\tprint('ok')\nSCRIPT";
    let (lang, code, rest) = detect_heredoc_reroute(tabbed).unwrap();
    assert_eq!(lang, "python");
    assert_eq!(code, "\tprint('ok')");
    assert!(rest.is_none());
}

/// #2164: a detached job that fails while a process it started still holds
/// its output pipe used to report "retained output withheld by storage
/// policy" with no stdout, no stderr and nothing archived. Its status poll
/// returns the captured streams, as a job without that process does.
#[test]
#[cfg_attr(windows, ignore)]
fn failed_background_job_with_lingering_child_returns_its_output() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
    let id = crate::server::background_shell::start(
        "sleep 4 & printf 'hello stdout\\n'; printf 'boom stderr\\n' >&2; exit 1".to_string(),
        ".".to_string(),
        std::collections::HashMap::default(),
        Some(30_000),
    );
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
    let snapshot = loop {
        let snapshot = crate::server::background_shell::snapshot(&id).expect("job is known");
        if !matches!(snapshot.state, JobState::Running { .. }) {
            break snapshot;
        }
        assert!(
            std::time::Instant::now() < deadline,
            "background job did not finish"
        );
        std::thread::sleep(std::time::Duration::from_millis(50));
    };
    assert!(
        snapshot.completeness.reader_incomplete,
        "the lingering child must hold the pipe for this test to cover #2164"
    );
    assert!(!snapshot.output_withheld, "the capture was withheld");

    let (text, outcome) = format_background_snapshot(&id, false, Some(snapshot));
    let outcome = background(outcome);
    assert_eq!(outcome.state, BackgroundJobState::Failed);
    assert_eq!(outcome.exit_code, Some(1));
    assert!(!text.contains("withheld by storage policy"), "{text}");
    assert!(text.contains("hello stdout"), "{text}");
    assert!(text.contains("boom stderr"), "{text}");
    assert_ne!(outcome.summary, "output withheld by storage policy");
}

#[test]
fn detect_heredoc_reroute_rejects_compound_prefix() {
    assert!(detect_heredoc_reroute("echo hi; python3 <<'PY'\nx\nPY").is_none());
    assert!(detect_heredoc_reroute("python3 -c 'print(1)'").is_none());
    assert!(detect_heredoc_reroute("python3 <<'PY' | cat\nx\nPY").is_none());
}

/// The `env` parameter reaches a lean-ctx the command starts just like an
/// inline `KEY=value` would: lean-ctx's own policy keys (the shell security
/// mode, its config location) are refused by name, so the call does not run.
#[test]
fn env_refuses_lean_ctx_policy_keys() {
    for (key, value) in [("LEAN_CTX_SHELL_SECURITY", "off"), ("HOME", "/tmp/x")] {
        let mut args = env_args(&[(key, value)]);
        args.insert(
            "command".to_string(),
            Value::String("lean-ctx -c 'bash -c id'".to_string()),
        );
        let error = collect_extra_env(&args).expect_err(key);
        assert!(
            error.contains(&format!("`{key}`")) && error.contains("nothing was run"),
            "{error}"
        );
    }
}

/// R6-1: ctx_shell's `env` argument is a channel the rights check reads. Under
/// a Developer profile, a git namespace variable in `env` (which
/// `collect_extra_env` does not block) is refused before the command runs, so
/// a merge cannot read a different object namespace than the gate verifies.
#[test]
fn session_rights_ctx_shell_env_namespace_keys_are_refused() {
    use crate::tools::registered::ctx_execute::session_rights_fixture::developer;
    let fx = developer(&[]);
    let ctx = ToolContext {
        project_root: fx.worktree.to_string_lossy().into_owned(),
        ..ToolContext::default()
    };
    lean_ctx::core::session_rights::sync_scope(fx.state(), || {
        for key in [
            "GIT_DIR",
            "GIT_REPLACE_REF_BASE",
            "GIT_GRAFT_FILE",
            "GIT_WORK_TREE",
        ] {
            let mut args = env_args(&[(key, "refs/x/")]);
            args.insert(
                "command".to_string(),
                Value::String("git merge 1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d".to_string()),
            );
            let out = CtxShellTool.handle(&args, &ctx).expect("a decision");
            assert_eq!(
                out.shell_outcome,
                Some(ShellOutcome::Blocked),
                "{key}: {}",
                out.text
            );
            assert!(
                out.text.contains(key) && out.text.contains("rule "),
                "{key}: {}",
                out.text
            );
        }
    });
}

/// GHSA-hqgc-cjh7-q3w4: the gates of an interpreter heredoc, judged by the
/// ctx_shell handler itself. Under `enforce`, with an allowlist that names
/// the interpreters, isolated config (no approved language, no inline
/// scripts).
#[cfg(unix)]
mod interpreter_heredoc_gate {
    use super::{CtxShellTool, McpTool, ShellOutcome, ToolContext, Value};
    use crate::tools::registered::ctx_execute::CtxExecuteTool;
    use serde_json::Map;

    fn enforce() -> lean_ctx::core::data_dir::IsolatedDataDir {
        let data = lean_ctx::core::data_dir::isolated_data_dir();
        lean_ctx::test_env::set_var("LEAN_CTX_SHELL_SECURITY", "enforce");
        lean_ctx::test_env::set_var(
            "LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE",
            "echo,cat,python3,node,ruby",
        );
        lean_ctx::test_env::remove_var("LEAN_CTX_SHELL_ALLOW_INLINE_SCRIPTS");
        data
    }

    fn reset() {
        lean_ctx::test_env::remove_var("LEAN_CTX_SHELL_SECURITY");
        lean_ctx::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
    }

    fn args(pairs: &[(&str, &str)]) -> Map<String, Value> {
        pairs
            .iter()
            .map(|(k, v)| ((*k).to_string(), Value::String((*v).to_string())))
            .collect()
    }

    fn shell(command: &str) -> crate::server::tool_trait::ToolOutput {
        CtxShellTool
            .handle(&args(&[("command", command)]), &ToolContext::default())
            .expect("a tool result")
    }

    fn unapproved(text: &str, language: &str) -> bool {
        text.contains(&format!("[BLOCKED] ctx_execute runs {language} code"))
    }

    /// The advisory's proof of concept and its delimiter forms: refused with
    /// ctx_execute's own refusal, nothing runs; once python is allowed for
    /// good, the same heredoc runs, and javascript still does not.
    #[test]
    #[serial_test::serial]
    fn an_interpreter_heredoc_needs_the_ctx_execute_approval() {
        let data = enforce();
        let marker = data.path().join("ran");
        let m = marker.to_string_lossy();
        let py_write = format!("open(r'{m}','w').write('ran')");
        let js_write = format!("require('fs').writeFileSync('{m}','ran')");
        let rb_write = format!("File.write('{m}','ran')");
        let refused = [
            (
                "python",
                "python3 <<'EOF'\nimport os\nprint('X'+os.getcwd())\nEOF".to_string(),
            ),
            ("python", format!("python3 <<'EOF'\n{py_write}\nEOF")),
            ("python", format!("python3 <<EOF\n{py_write}\nEOF")),
            ("python", format!("python3 - <<\"PY\"\n{py_write}\nPY")),
            ("python", format!("python3 <<-EOF\n\t{py_write}\n\tEOF")),
            (
                "python",
                format!("PYTHONDONTWRITEBYTECODE=1 python3 <<EOF\n{py_write}\nEOF"),
            ),
            ("javascript", format!("node <<'JS'\n{js_write}\nJS")),
            ("ruby", format!("ruby <<RB\n{rb_write}\nRB")),
        ];
        for (language, command) in &refused {
            assert!(
                super::detect_heredoc_reroute(command).is_some(),
                "the reroute applies: {command:?}"
            );
            let out = shell(command);
            assert_eq!(
                out.shell_outcome,
                Some(ShellOutcome::Blocked),
                "{command:?}: {}",
                out.text
            );
            assert!(unapproved(&out.text, language), "{command:?}: {}", out.text);
            assert!(!out.text.contains("X/"), "the heredoc ran: {}", out.text);
            assert!(!marker.exists(), "the heredoc ran: {command:?}");
        }
        // Parity: ctx_execute refuses the same code with the same message.
        let direct = CtxExecuteTool
            .handle(
                &args(&[("language", "python"), ("code", "print(1)")]),
                &ToolContext::default(),
            )
            .expect("a tool result");
        assert_eq!(direct.shell_outcome, Some(ShellOutcome::Blocked));
        assert!(unapproved(&direct.text, "python"), "{}", direct.text);

        lean_ctx_shell_policy::allow_execute_languages(&["python".to_string()])
            .expect("allow python");
        let out = shell("python3 <<'EOF'\nimport os\nprint('X'+os.getcwd())\nEOF");
        assert_eq!(
            out.shell_outcome,
            Some(ShellOutcome::Exit(0)),
            "{}",
            out.text
        );
        assert!(out.text.contains("X/"), "{}", out.text);
        assert!(
            out.text.contains("auto-rerouted to ctx_execute"),
            "{}",
            out.text
        );
        let out = shell(&format!("node <<'JS'\n{js_write}\nJS"));
        assert!(unapproved(&out.text, "javascript"), "{}", out.text);
        assert!(!marker.exists(), "node ran");
        reset();
    }

    /// The session's rights profile refuses other languages: an allowed
    /// language does not open the heredoc, and the shell gate is not asked.
    #[test]
    #[serial_test::serial]
    fn a_rights_profile_refuses_an_interpreter_heredoc() {
        let data = enforce();
        lean_ctx::test_env::set_var("LEAN_CTX_SHELL_ALLOW_INLINE_SCRIPTS", "1");
        lean_ctx_shell_policy::allow_execute_languages(&["python".to_string()])
            .expect("allow python");
        let fx = crate::tools::registered::ctx_execute::session_rights_fixture::developer(&[]);
        let ctx = ToolContext {
            project_root: fx.worktree.to_string_lossy().into_owned(),
            ..ToolContext::default()
        };
        let marker = data.path().join("ran");
        let command = format!(
            "python3 <<'EOF'\nopen(r'{}','w').write('ran')\nEOF",
            marker.to_string_lossy()
        );
        lean_ctx::core::session_rights::sync_scope(fx.state(), || {
            let out = CtxShellTool
                .handle(&args(&[("command", &command)]), &ctx)
                .expect("a tool result");
            assert_eq!(
                out.shell_outcome,
                Some(ShellOutcome::Blocked),
                "{}",
                out.text
            );
        });
        assert!(!marker.exists(), "the heredoc ran under the profile");
        lean_ctx::test_env::remove_var("LEAN_CTX_SHELL_ALLOW_INLINE_SCRIPTS");
        reset();
    }

    /// A context with a session, so the shell remainder of a rerouted heredoc
    /// gets its validated working directory.
    fn session_ctx(
        root: &std::path::Path,
        cancel: Option<tokio_util::sync::CancellationToken>,
    ) -> ToolContext {
        ToolContext {
            project_root: root.to_string_lossy().into_owned(),
            session: Some(std::sync::Arc::new(tokio::sync::RwLock::new(
                lean_ctx::core::session::SessionState::new(),
            ))),
            cancel,
            ..ToolContext::default()
        }
    }

    fn remainder_job(out: &crate::server::tool_trait::ToolOutput) -> String {
        match &out.shell_outcome {
            Some(ShellOutcome::Background(bg)) => bg.job_id.clone(),
            other => panic!("expected a detached remainder, got {other:?}: {}", out.text),
        }
    }

    /// The shell remainder of a rerouted heredoc keeps the foreground soft
    /// cap: a long remainder detaches to a pollable job instead of holding
    /// the call past the host's abort, and the interpreter half's output is
    /// still delivered.
    #[test]
    #[serial_test::serial]
    fn a_long_heredoc_remainder_detaches_at_the_soft_cap() {
        let data = enforce();
        lean_ctx::test_env::set_var(
            "LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE",
            "echo,cat,python3,node,ruby,sleep",
        );
        lean_ctx::test_env::set_var("LEAN_CTX_SHELL_FG_CAP_MS", "300");
        lean_ctx_shell_policy::allow_execute_languages(&["python".to_string()])
            .expect("allow python");
        let ctx = session_ctx(data.path(), None);
        let started = std::time::Instant::now();
        let out = CtxShellTool
            .handle(
                &args(&[(
                    "command",
                    "python3 <<'EOF'\nprint('heredoc-half')\nEOF\nsleep 30",
                )]),
                &ctx,
            )
            .expect("a tool result");
        let job = remainder_job(&out);
        assert!(
            started.elapsed() < std::time::Duration::from_secs(20),
            "the remainder held the call past the cap"
        );
        assert!(out.text.contains("heredoc-half"), "{}", out.text);
        assert!(
            out.text.contains(&format!("auto-background:{job}")),
            "{}",
            out.text
        );
        let _ = crate::server::background_shell::cancel_snapshot(&job);
        lean_ctx::test_env::remove_var("LEAN_CTX_SHELL_FG_CAP_MS");
        reset();
    }

    /// A cancelled call stops waiting for the remainder at once; the job stays
    /// pollable, as on the non-rerouted path (#1106).
    #[test]
    #[serial_test::serial]
    fn a_cancelled_call_stops_waiting_for_the_heredoc_remainder() {
        let data = enforce();
        lean_ctx::test_env::set_var(
            "LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE",
            "echo,cat,python3,node,ruby,sleep",
        );
        lean_ctx_shell_policy::allow_execute_languages(&["python".to_string()])
            .expect("allow python");
        let token = tokio_util::sync::CancellationToken::new();
        token.cancel();
        let ctx = session_ctx(data.path(), Some(token));
        let started = std::time::Instant::now();
        let out = CtxShellTool
            .handle(
                &args(&[("command", "python3 <<'EOF'\nprint(1)\nEOF\nsleep 30")]),
                &ctx,
            )
            .expect("a tool result");
        let job = remainder_job(&out);
        assert!(
            started.elapsed() < std::time::Duration::from_secs(20),
            "a cancelled call kept waiting for the remainder"
        );
        let _ = crate::server::background_shell::cancel_snapshot(&job);
        reset();
    }
}

/// #2279: a session lock another reader holds only skips the session update.
/// It used to divert the command onto a bare path without the foreground soft
/// cap and without the request's cancellation, so a cancelled call held its
/// handler thread (and its child) for the whole command timeout. The call
/// must come back promptly, and its unshared job must be stopped.
#[test]
#[cfg(unix)]
fn busy_session_lock_still_honours_request_cancellation() {
    let _data = lean_ctx::core::data_dir::isolated_data_dir();
    let root = tempfile::tempdir().unwrap();
    let session = std::sync::Arc::new(tokio::sync::RwLock::new(
        lean_ctx::core::session::SessionState::new(),
    ));
    // A long-lived reader: the call's own cwd read succeeds, its write for
    // the session update cannot, which is the degraded case.
    let reader = session.clone().try_read_owned().unwrap();
    let token = tokio_util::sync::CancellationToken::new();
    token.cancel();
    let ctx = ToolContext {
        project_root: root.path().to_string_lossy().into_owned(),
        session: Some(session),
        cancel: Some(token),
        ..ToolContext::default()
    };
    let mut args = Map::new();
    args.insert("command".to_string(), Value::String("sleep 39".to_string()));
    args.insert("timeout_ms".to_string(), Value::from(60_000));
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .worker_threads(2)
        .enable_all()
        .build()
        .unwrap();
    let started = std::time::Instant::now();
    let output = runtime
        .block_on(
            async move { tokio::spawn(async move { CtxShellTool.handle(&args, &ctx) }).await },
        )
        .unwrap()
        .expect("a tool result");
    let elapsed = started.elapsed();
    drop(reader);
    assert!(
        elapsed < std::time::Duration::from_secs(10),
        "a cancelled call under a busy session lock took {elapsed:?}: {}",
        output.text
    );
    let Some(ShellOutcome::Background(outcome)) = output.shell_outcome else {
        panic!(
            "expected the detached shape, got {:?}",
            output.shell_outcome
        );
    };
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    while matches!(
        crate::server::background_shell::status(&outcome.job_id),
        Some(JobState::Running { .. })
    ) && std::time::Instant::now() < deadline
    {
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
    assert!(
        matches!(
            crate::server::background_shell::status(&outcome.job_id),
            Some(JobState::Cancelled { .. })
        ),
        "the cancelled call's job must be stopped"
    );
}