supercode-harness 0.4.8

The optional native Supercode agent and tool harness
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
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
//! §2 module 28 `lsp` (COMPOSABLE-HARNESS-DESIGN.md line 478): "D1 LSP
//! diagnostics in edit path + query tool" — this module ships the
//! WEAKEST FORM that satisfies D1: server LIFECYCLE for a HANDFUL of
//! user-configured language servers, and diagnostics surfaced in the
//! edit/write TOOL RESULT via the shared D-5 write-path seam
//! ([`crate::tools::WriteObserver`], P5-9/P5-11).
//!
//! # Honest, deliberate gaps (design §4.4 "LSP-in-edit at fleet scale")
//! - **No auto-spawn/auto-download fleet.** opencode auto-provisions ~38
//!   language servers. This module only ever spawns a server the user
//!   EXPLICITLY configured under `[capabilities.lsp.servers.<name>]` — no
//!   network fetch, no bundled binaries, nothing runs that wasn't named in
//!   config.
//! - **No `/find/symbol` symbol-indexing query tool.** A real symbol index
//!   (workspace/symbol, textDocument/definition, ...) is D-4-sized work
//!   this module does not attempt — shipping a `lsp.query` tool that
//!   silently no-ops would be a worse outcome than not shipping it (build
//!   brief: "if you expose any query surface, it must work or not
//!   exist"), so none is exposed. `[capabilities.lsp]` carries exactly two
//!   real, wired knobs: `enabled` and `servers` (plus the bounds
//!   `max_diagnostics`/`timeout_secs`) — no `query`/`symbols` key is ever
//!   parsed, so there is no declared-but-dead knob for either gap.
//!
//! # Wire protocol — hand-rolled, no new dependency
//! LSP frames a JSON-RPC message behind a tiny HTTP-style header
//! (`Content-Length: N\r\n\r\n<N bytes of JSON>`). That framing is a dozen
//! lines over `tokio::io::AsyncBufReadExt`/`AsyncReadExt` — pulling in a
//! dedicated `lsp-types`/`lsp-server` crate for it would be the heavy,
//! over-built option for a module scoped to lifecycle + diagnostics over a
//! handful of servers (no symbol index, no code actions, no incremental
//! sync deltas — just `initialize`/`initialized`/`didOpen`/`didChange`/
//! `publishDiagnostics`/`shutdown`/`exit`), so `write_message`/
//! `read_message` below hand-roll it instead. `cargo deny check` has
//! nothing new to license-audit as a result.
//!
//! # Process lifecycle (no orphaned language servers, incl. grandchildren)
//! A server is a long-lived child process, spawned lazily
//! ([`LspManager::diagnostics_after_write`], on the first write to a file
//! extension it's configured for) and kept alive in [`LspManager`] for
//! reuse across writes. A real configured server (`rust-analyzer`,
//! `typescript-language-server`, `gopls`, ...) commonly spawns its OWN
//! persistent worker subprocesses (a proc-macro/build server, `tsserver`,
//! `go`, ...) — so `.kill_on_drop(true)`/`Child::start_kill` alone (which
//! only ever signal the ONE directly-tracked pid) are not enough; this is
//! the SAME grandchild-orphan class `crate::agent::kill_job_process_group`
//! was built to close for background shell jobs (P5-6), and the fix here
//! reuses that exact mechanism: `LspClient::spawn` puts the server in its
//! OWN process group (`Command::process_group(0)`, unix), and
//! `LspClient::kill` SIGKILLs the WHOLE group (`kill_process_group`),
//! not just the leader — `.kill_on_drop(true)` remains as a second,
//! independent backstop for the leader pid specifically. On non-unix
//! targets, no portable process-group primitive is wired up (same posture
//! as `kill_job_process_group`'s own `#[cfg(not(unix))]` arm) — this falls
//! back to the pre-fix direct-child-only kill, a documented residual, not
//! silently claimed fixed there.
//!
//! [`LspManager::kill_all_sync`] (this module's group-kill, above) is
//! called from `impl Drop for crate::Agent` — the ONLY production teardown
//! path today, provable/traceable rather than relying solely on
//! `kill_on_drop(true)`'s implicit runtime behavior. [`LspManager::shutdown_all`]
//! (a graceful LSP `shutdown`/`exit` handshake, letting a well-behaved
//! server reap its own children before this module force-kills the group)
//! is NOT wired into any automatic path — `Agent::run_loop` runs once PER
//! TURN, not once per session, so calling it there would tear down and
//! respawn a reused server every turn, defeating the "kept alive for reuse
//! across writes" design above; there is no separate session-level
//! clean-exit hook distinct from `Drop` in this codebase today. It remains
//! available as public API (exercised directly by this module's own tests)
//! for a caller that manages its own `Agent` lifecycle and wants to drain
//! gracefully before dropping it — but nothing calls it automatically, and
//! that is the honest, current state (not an aspirational claim about a
//! code path that doesn't exist).

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

use serde_json::{json, Value};
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};

use crate::error::{Error, Result};

/// Hardening cap (same rationale as `crate::mcp::MCP_MAX_RESPONSE_BYTES`):
/// the largest single Content-Length-framed message this client will
/// buffer before treating the server as hostile/broken and erroring out —
/// bounds how much memory a misbehaving configured language server can
/// force this process to allocate for one message.
pub const LSP_MAX_MESSAGE_BYTES: usize = 16 * 1024 * 1024;

/// Default cap on the number of diagnostics rendered into a single tool
/// result (bounded-context requirement — build brief: "a flood mustn't
/// blow context"). Overridable via `[capabilities.lsp] max_diagnostics`.
pub const DEFAULT_LSP_MAX_DIAGNOSTICS: usize = 20;

/// Default wait for a configured server to publish diagnostics after a
/// `didOpen`/`didChange` before giving up gracefully (never blocking the
/// tool call indefinitely). Overridable via `[capabilities.lsp] timeout_secs`.
pub const DEFAULT_LSP_TIMEOUT_SECS: u64 = 5;

/// One `[capabilities.lsp.servers.<name>]` entry — a user-configured
/// language server this module is allowed to spawn. `command`/`args` are
/// config-borne code execution (D-10) — see `crate::configfile::sanitize_for_project`
/// / `crate::userconfig`'s project-strip, which refuses this table from an
/// untrusted project layer exactly like `hooks`/`mcp.servers`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LspServerSpec {
    /// The executable to spawn (searched on `PATH` like any `Command::new`).
    pub command: String,
    /// Extra arguments passed to `command`.
    pub args: Vec<String>,
    /// File extensions (with or without a leading `.`, matched case-
    /// insensitively) this server handles — a write to a matching path
    /// lazily spawns (or reuses) this server.
    pub extensions: Vec<String>,
}

/// One diagnostic surfaced from a server's `textDocument/publishDiagnostics`
/// notification — the small subset of the LSP `Diagnostic` shape this
/// module renders into a tool result (no `code`/`source`/`relatedInformation`
/// — weakest form).
#[derive(Debug, Clone, PartialEq, Eq)]
struct DiagnosticEntry {
    severity: &'static str,
    line: u32,
    character: u32,
    message: String,
}

/// Per-connection JSON-RPC-over-stdio state — bundled behind ONE
/// `tokio::sync::Mutex` (rather than separate locks for stdin/stdout) so a
/// full request/response (or notify+wait-for-push) cycle runs atomically:
/// two concurrent writes to files the SAME server handles can never
/// interleave their reads and steal each other's response/diagnostics.
struct LspIo {
    stdin: tokio::process::ChildStdin,
    stdout: BufReader<tokio::process::ChildStdout>,
    next_id: i64,
    /// uri -> last-sent document version (LSP full-text sync: `didOpen`
    /// sends version 1, every subsequent `didChange` increments it).
    opened: HashMap<String, i64>,
    /// Whether `initialize`/`initialized` has completed on this connection.
    initialized: bool,
}

/// A live connection to one configured language server — one spawned child
/// process, kept alive for reuse across writes to files it handles.
#[derive(Debug)]
pub struct LspClient {
    name: String,
    // Sync `Mutex` (not `tokio::sync::Mutex`): only ever touched via the
    // synchronous `start_kill`/`try_wait` (never awaited while held) — see
    // `crate::agent::kill_job_process_group`'s identical precedent, which
    // is exactly why this can be called from the non-async `impl Drop for
    // Agent::drop`.
    child: std::sync::Mutex<tokio::process::Child>,
    io: tokio::sync::Mutex<LspIo>,
}

impl std::fmt::Debug for LspIo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LspIo")
            .field("next_id", &self.next_id)
            .field("opened", &self.opened.keys().collect::<Vec<_>>())
            .field("initialized", &self.initialized)
            .finish()
    }
}

/// Write one JSON-RPC value with LSP's `Content-Length` header framing.
async fn write_message(stdin: &mut tokio::process::ChildStdin, val: &Value) -> Result<()> {
    let body = serde_json::to_vec(val).map_err(|e| Error::tool("lsp", format!("encode: {e}")))?;
    let header = format!("Content-Length: {}\r\n\r\n", body.len());
    stdin
        .write_all(header.as_bytes())
        .await
        .map_err(|e| Error::tool("lsp", format!("write: {e}")))?;
    stdin
        .write_all(&body)
        .await
        .map_err(|e| Error::tool("lsp", format!("write: {e}")))?;
    stdin
        .flush()
        .await
        .map_err(|e| Error::tool("lsp", format!("flush: {e}")))?;
    Ok(())
}

/// Read one JSON-RPC value framed with LSP's `Content-Length` header —
/// bounded by [`LSP_MAX_MESSAGE_BYTES`], and errors (rather than hangs) on
/// EOF (the server exited or closed its stdout).
async fn read_message(stdout: &mut BufReader<tokio::process::ChildStdout>) -> Result<Value> {
    let mut content_length: Option<usize> = None;
    loop {
        let mut line = String::new();
        let n = stdout
            .read_line(&mut line)
            .await
            .map_err(|e| Error::tool("lsp", format!("read: {e}")))?;
        if n == 0 {
            return Err(Error::tool("lsp", "server closed stdout (eof)"));
        }
        let trimmed = line.trim_end_matches(['\r', '\n']);
        if trimmed.is_empty() {
            break; // blank line ends the header block
        }
        if let Some(v) = trimmed.strip_prefix("Content-Length:") {
            content_length = v.trim().parse().ok();
        }
        // Any other header (e.g. `Content-Type:`) is read and ignored.
    }
    let len = content_length
        .ok_or_else(|| Error::tool("lsp", "message missing Content-Length header"))?;
    if len > LSP_MAX_MESSAGE_BYTES {
        return Err(Error::tool(
            "lsp",
            format!("message too large ({len} bytes) — refusing to buffer"),
        ));
    }
    let mut buf = vec![0u8; len];
    stdout
        .read_exact(&mut buf)
        .await
        .map_err(|e| Error::tool("lsp", format!("read body: {e}")))?;
    serde_json::from_slice(&buf).map_err(|e| Error::tool("lsp", format!("decode: {e}")))
}

/// `file://` URI for `path` — a minimal, deterministic encoding (no
/// percent-escaping beyond backslash normalization) sufficient for the
/// stdio-local servers this module targets; every server this module talks
/// to is a local child process reading the SAME literal path this process
/// resolved, so round-trip fidelity (not RFC 3986 completeness) is what
/// matters.
fn path_to_uri(path: &Path) -> String {
    let s = path.to_string_lossy().replace('\\', "/");
    if let Some(stripped) = s.strip_prefix('/') {
        format!("file:///{stripped}")
    } else {
        format!("file:///{s}")
    }
}

/// Best-effort LSP `languageId` for `path`'s extension — covers the common
/// languages a configured server would plausibly handle; unrecognized
/// extensions fall back to `"plaintext"` (a server that cares can still use
/// the extension embedded in the uri).
fn language_id_for(path: &Path) -> &'static str {
    match path
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or_default()
        .to_ascii_lowercase()
        .as_str()
    {
        "rs" => "rust",
        "py" => "python",
        "js" | "mjs" | "cjs" => "javascript",
        "jsx" => "javascriptreact",
        "ts" | "mts" | "cts" => "typescript",
        "tsx" => "typescriptreact",
        "go" => "go",
        "rb" => "ruby",
        "java" => "java",
        "c" | "h" => "c",
        "cpp" | "cc" | "cxx" | "hpp" => "cpp",
        "cs" => "csharp",
        "json" => "json",
        "toml" => "toml",
        "yaml" | "yml" => "yaml",
        "md" => "markdown",
        "sh" | "bash" => "shellscript",
        _ => "plaintext",
    }
}

/// SIGKILL an entire process group — the shared grandchild-orphan-fix
/// primitive, same mechanism as `crate::agent::kill_job_process_group`
/// (P5-6). `pid` must be a process-group LEADER's pid (i.e. the process was
/// spawned with `Command::process_group(0)`, making its pgid equal its own
/// pid) for `-(pid)` to address the whole group rather than just the
/// leader. Reused by `crate::formatters` for the same reason — see
/// `crate::formatters::run_formatter`'s timeout arm.
///
/// SAFETY: `libc::kill` with a negative pid is `killpg` — it only ever
/// sends a signal (never dereferences memory), so this is safe regardless
/// of whether the group is still alive; a group that already exited yields
/// `ESRCH`, a documented no-op, not an error worth surfacing.
#[cfg(unix)]
pub(crate) fn kill_process_group(pid: u32) {
    unsafe {
        libc::kill(-(pid as libc::pid_t), libc::SIGKILL);
    }
}

fn severity_label(sev: Option<i64>) -> &'static str {
    match sev {
        Some(1) => "error",
        Some(2) => "warning",
        Some(3) => "information",
        Some(4) => "hint",
        _ => "diagnostic",
    }
}

/// `true` iff `msg` is a `textDocument/publishDiagnostics` notification for
/// `uri` specifically (a server may publish for OTHER files it opened as
/// part of project analysis — those are ignored, never mixed into this
/// write's result).
fn is_publish_diagnostics_for(msg: &Value, uri: &str) -> bool {
    msg.get("method").and_then(|m| m.as_str()) == Some("textDocument/publishDiagnostics")
        && msg
            .get("params")
            .and_then(|p| p.get("uri"))
            .and_then(|u| u.as_str())
            == Some(uri)
}

/// Parse a `publishDiagnostics` notification's `diagnostics` array into
/// `(true_total_count, bounded_entries)` — `true_total_count` may exceed
/// `entries.len()` when the server reported more than `cap`, so the caller
/// can render an honest "N more not shown" instead of silently dropping
/// them.
fn diagnostics_from_message(msg: &Value, cap: usize) -> (usize, Vec<DiagnosticEntry>) {
    let Some(arr) = msg
        .get("params")
        .and_then(|p| p.get("diagnostics"))
        .and_then(|d| d.as_array())
    else {
        return (0, Vec::new());
    };
    let total = arr.len();
    let entries = arr
        .iter()
        .take(cap)
        .map(|d| DiagnosticEntry {
            severity: severity_label(d.get("severity").and_then(|s| s.as_i64())),
            line: d
                .get("range")
                .and_then(|r| r.get("start"))
                .and_then(|s| s.get("line"))
                .and_then(|v| v.as_u64())
                .unwrap_or(0) as u32,
            character: d
                .get("range")
                .and_then(|r| r.get("start"))
                .and_then(|s| s.get("character"))
                .and_then(|v| v.as_u64())
                .unwrap_or(0) as u32,
            message: d
                .get("message")
                .and_then(|m| m.as_str())
                .unwrap_or_default()
                .to_string(),
        })
        .collect();
    (total, entries)
}

/// Max characters kept from a single diagnostic's message text — a
/// pathological server can't blow context with one enormous message
/// either, on top of the diagnostics-COUNT cap.
const MAX_DIAGNOSTIC_MESSAGE_CHARS: usize = 400;

fn format_diagnostics(
    server: &str,
    path: &Path,
    total: usize,
    entries: &[DiagnosticEntry],
) -> String {
    let mut out = format!(
        "LSP diagnostics ({server}) for {}: {total} issue(s)",
        path.display()
    );
    for d in entries {
        let mut msg = d.message.clone();
        if msg.chars().count() > MAX_DIAGNOSTIC_MESSAGE_CHARS {
            msg = msg.chars().take(MAX_DIAGNOSTIC_MESSAGE_CHARS).collect();
            msg.push('\u{2026}');
        }
        out.push_str(&format!(
            "\n  {}:{}: {}: {}",
            d.line + 1,
            d.character + 1,
            d.severity,
            msg
        ));
    }
    if total > entries.len() {
        out.push_str(&format!(
            "\n  ... and {} more diagnostic(s) not shown",
            total - entries.len()
        ));
    }
    out
}

impl LspClient {
    /// Spawn `spec.command` and hold it open, uninitialized (the LSP
    /// `initialize` handshake happens lazily, under the SAME `io` lock as
    /// the first `didOpen`, in [`Self::open_or_change_and_diagnose`]).
    /// `.kill_on_drop(true)` mirrors `crate::mcp::McpClient::connect`'s own
    /// stdio precedent — reaps the server if this client is ever dropped
    /// without an explicit [`Self::kill`]/[`Self::shutdown`].
    ///
    /// `.process_group(0)` (unix) puts the server in its OWN new process
    /// group (pgid == its own pid) — see the module doc's "Process
    /// lifecycle" section and `crate::agent::kill_job_process_group` for
    /// why: it's what lets [`Self::kill`] SIGKILL the server's WORKER
    /// grandchildren (proc-macro/build servers, `tsserver`, `go`, ...) too,
    /// not just this one directly-tracked pid.
    async fn spawn(name: &str, spec: &LspServerSpec) -> Result<Arc<LspClient>> {
        let mut cmd = tokio::process::Command::new(&spec.command);
        cmd.args(&spec.args)
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::null())
            .kill_on_drop(true);
        #[cfg(unix)]
        cmd.process_group(0);
        let mut child = cmd
            .spawn()
            .map_err(|e| Error::tool("lsp", format!("spawn {}: {e}", spec.command)))?;
        let stdin = child
            .stdin
            .take()
            .ok_or_else(|| Error::tool("lsp", "no stdin"))?;
        let stdout = BufReader::new(
            child
                .stdout
                .take()
                .ok_or_else(|| Error::tool("lsp", "no stdout"))?,
        );
        Ok(Arc::new(LspClient {
            name: name.to_string(),
            child: std::sync::Mutex::new(child),
            io: tokio::sync::Mutex::new(LspIo {
                stdin,
                stdout,
                next_id: 0,
                opened: HashMap::new(),
                initialized: false,
            }),
        }))
    }

    /// The full D1 cycle for one write: ensure `initialize`/`initialized`
    /// has happened once, send `didOpen` (first touch of this uri) or
    /// `didChange` (subsequent touches, full-text sync), then read
    /// messages until this uri's `publishDiagnostics` notification arrives
    /// or `timeout` elapses. Holds the `io` lock for the whole cycle —
    /// see [`LspIo`]'s doc comment for why that's required, not just
    /// convenient.
    async fn open_or_change_and_diagnose(
        &self,
        root: &Path,
        uri: &str,
        text: &str,
        language_id: &str,
        timeout: Duration,
        cap: usize,
    ) -> Result<(usize, Vec<DiagnosticEntry>)> {
        let mut io = self.io.lock().await;

        if !io.initialized {
            let id = io.next_id;
            io.next_id += 1;
            let req = json!({
                "jsonrpc": "2.0",
                "id": id,
                "method": "initialize",
                "params": {
                    "processId": std::process::id(),
                    "rootUri": path_to_uri(root),
                    "capabilities": {},
                }
            });
            write_message(&mut io.stdin, &req).await?;
            let deadline = tokio::time::Instant::now() + timeout;
            loop {
                let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
                if remaining.is_zero() {
                    return Err(Error::tool(
                        "lsp",
                        "timed out waiting for initialize response",
                    ));
                }
                let msg = tokio::time::timeout(remaining, read_message(&mut io.stdout))
                    .await
                    .map_err(|_| {
                        Error::tool("lsp", "timed out waiting for initialize response")
                    })??;
                if msg.get("id").and_then(|v| v.as_i64()) == Some(id) {
                    break; // the initialize response — ignore any notification before it
                }
            }
            let notif = json!({"jsonrpc": "2.0", "method": "initialized", "params": {}});
            write_message(&mut io.stdin, &notif).await?;
            io.initialized = true;
        }

        let msg = match io.opened.get(uri).copied() {
            Some(version) => {
                let next = version + 1;
                io.opened.insert(uri.to_string(), next);
                json!({
                    "jsonrpc": "2.0",
                    "method": "textDocument/didChange",
                    "params": {
                        "textDocument": {"uri": uri, "version": next},
                        "contentChanges": [{"text": text}],
                    }
                })
            }
            None => {
                io.opened.insert(uri.to_string(), 1);
                json!({
                    "jsonrpc": "2.0",
                    "method": "textDocument/didOpen",
                    "params": {
                        "textDocument": {
                            "uri": uri,
                            "languageId": language_id,
                            "version": 1,
                            "text": text,
                        }
                    }
                })
            }
        };
        write_message(&mut io.stdin, &msg).await?;

        let deadline = tokio::time::Instant::now() + timeout;
        loop {
            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
            if remaining.is_zero() {
                return Err(Error::tool("lsp", "timed out waiting for diagnostics"));
            }
            let msg = tokio::time::timeout(remaining, read_message(&mut io.stdout))
                .await
                .map_err(|_| Error::tool("lsp", "timed out waiting for diagnostics"))??;
            if is_publish_diagnostics_for(&msg, uri) {
                return Ok(diagnostics_from_message(&msg, cap));
            }
            // Some other notification (or a server-initiated request this
            // weakest-form client doesn't answer) — ignore and keep
            // waiting for OUR diagnostics, bounded by `deadline` above.
        }
    }

    /// Real, synchronous OS-process kill — callable from the non-async
    /// `impl Drop for Agent` (same reasoning as
    /// `crate::agent::kill_job_process_group`). SIGKILLs the server's WHOLE
    /// process group (unix) — see [`Self::spawn`]'s `.process_group(0)` and
    /// `kill_process_group` — so worker grandchildren die too, not just
    /// this directly-tracked pid; falls back to the direct-child-only kill
    /// on non-unix. A no-op if the process already exited.
    fn kill(&self) {
        if let Ok(mut child) = self.child.lock() {
            #[cfg(unix)]
            if let Some(pid) = child.id() {
                kill_process_group(pid);
            }
            let _ = child.start_kill();
            let _ = child.try_wait();
        }
    }

    /// Graceful shutdown: `shutdown` request, brief wait for its response,
    /// `exit` notification — then [`Self::kill`] unconditionally as a
    /// backstop (a server that ignores `exit` must not linger). Bounded to
    /// 2s total so a hung server can never block session teardown.
    async fn shutdown(&self) {
        let graceful = async {
            let mut io = self.io.lock().await;
            if !io.initialized {
                return; // never handshaked — nothing to shut down gracefully
            }
            let id = io.next_id;
            io.next_id += 1;
            let req = json!({"jsonrpc": "2.0", "id": id, "method": "shutdown", "params": null});
            if write_message(&mut io.stdin, &req).await.is_ok() {
                let _ =
                    tokio::time::timeout(Duration::from_millis(500), read_message(&mut io.stdout))
                        .await;
            }
            let notif = json!({"jsonrpc": "2.0", "method": "exit", "params": null});
            let _ = write_message(&mut io.stdin, &notif).await;
        };
        let _ = tokio::time::timeout(Duration::from_secs(2), graceful).await;
        self.kill();
    }
}

/// Session-scoped registry of configured language servers and the live
/// connections spawned so far — the [`crate::tools::WriteObserver`] this
/// module installs ([`LspDiagnosticsObserver`]) is a thin wrapper around a
/// shared `Arc<LspManager>`; `crate::agent::build_tool_context` keeps its
/// own `Arc` clone too, so `crate::Agent`'s `Drop` impl can reach
/// [`Self::kill_all_sync`] regardless of how many observer clones exist.
#[derive(Debug)]
pub struct LspManager {
    servers: std::sync::Mutex<HashMap<String, Arc<LspClient>>>,
    specs: Vec<(String, LspServerSpec)>,
    root: PathBuf,
    timeout: Duration,
    max_diagnostics: usize,
}

impl LspManager {
    /// Build a manager over `specs` (name -> server definition), rooted at
    /// `root` (used as the LSP `rootUri` and the containment floor every
    /// touched path is checked against via `crate::safe_path::contained`).
    pub fn new(
        root: PathBuf,
        specs: Vec<(String, LspServerSpec)>,
        timeout: Duration,
        max_diagnostics: usize,
    ) -> Self {
        LspManager {
            servers: std::sync::Mutex::new(HashMap::new()),
            specs,
            root,
            timeout,
            max_diagnostics,
        }
    }

    fn spec_for_extension(&self, path: &Path) -> Option<(String, LspServerSpec)> {
        let ext = path
            .extension()
            .and_then(|e| e.to_str())?
            .to_ascii_lowercase();
        self.specs
            .iter()
            .find(|(_, s)| {
                s.extensions
                    .iter()
                    .any(|e| e.trim_start_matches('.').to_ascii_lowercase() == ext)
            })
            .cloned()
    }

    async fn get_or_spawn(&self, name: &str, spec: &LspServerSpec) -> Result<Arc<LspClient>> {
        if let Some(existing) = self.servers.lock().unwrap().get(name).cloned() {
            return Ok(existing);
        }
        let client = LspClient::spawn(name, spec).await?;
        let mut map = self.servers.lock().unwrap();
        // A concurrent write to another file this SAME server handles may
        // have raced this spawn and already inserted — keep whichever
        // landed first (the loser's freshly-spawned child is dropped here,
        // which reaps it via `kill_on_drop`, never leaked).
        let winner = map.entry(name.to_string()).or_insert(client).clone();
        Ok(winner)
    }

    /// D1: the write-path diagnostics hook — spawns (or reuses) the
    /// configured server for `path`'s extension, if any, sends
    /// `didOpen`/`didChange` with the file's CURRENT on-disk content (the
    /// caller — `LspDiagnosticsObserver::after_write` — only calls this
    /// once the write has completed, so this always reads the FINAL bytes,
    /// which for `[capabilities.formatters]` also on means the FORMATTED
    /// content, not the model's pre-format draft — see the observer
    /// ordering `crate::agent::build_tool_context` installs), and waits
    /// (bounded by `self.timeout`) for that file's diagnostics. Never
    /// fails the caller: every error (no configured server, spawn
    /// failure, protocol error, timeout) degrades to `None`, logged once
    /// via `tracing::warn!`.
    pub async fn diagnostics_after_write(&self, path: &Path) -> Option<String> {
        if !crate::safe_path::contained(&self.root, path) {
            return None; // out of this module's scope — never touch outside the project
        }
        let (name, spec) = self.spec_for_extension(path)?;
        let client = match self.get_or_spawn(&name, &spec).await {
            Ok(c) => c,
            Err(e) => {
                tracing::warn!(server = %name, "lsp: failed to spawn/reuse server: {e}");
                return None;
            }
        };
        let text = match tokio::fs::read_to_string(path).await {
            Ok(t) => t,
            Err(_) => return None, // deleted/unreadable — nothing to diagnose
        };
        let uri = path_to_uri(path);
        let language_id = language_id_for(path);
        match client
            .open_or_change_and_diagnose(
                &self.root,
                &uri,
                &text,
                language_id,
                self.timeout,
                self.max_diagnostics,
            )
            .await
        {
            Ok((total, entries)) if total > 0 => {
                Some(format_diagnostics(&client.name, path, total, &entries))
            }
            Ok(_) => None, // clean file — no noise on every write
            Err(e) => {
                tracing::warn!(server = %name, "lsp: diagnostics unavailable: {e}");
                None
            }
        }
    }

    /// Real, synchronous, provable kill of every server this manager has
    /// spawned so far — called from `impl Drop for crate::Agent` (a
    /// non-async context, hence the sync signature). A no-op for any
    /// server already exited.
    pub fn kill_all_sync(&self) {
        let drained: Vec<Arc<LspClient>> = self
            .servers
            .lock()
            .map(|mut m| m.drain().map(|(_, c)| c).collect())
            .unwrap_or_default();
        for client in drained {
            client.kill();
        }
    }

    /// Graceful async shutdown of every server this manager has spawned —
    /// `shutdown`/`exit` handshake per server, `kill_all_sync`-equivalent
    /// backstop applied per-client by `LspClient::shutdown` itself. Use
    /// this on a clean-exit path that can afford to `.await`; use
    /// [`Self::kill_all_sync`] from `Drop`.
    pub async fn shutdown_all(&self) {
        let drained: Vec<Arc<LspClient>> = self
            .servers
            .lock()
            .map(|mut m| m.drain().map(|(_, c)| c).collect())
            .unwrap_or_default();
        for client in drained {
            client.shutdown().await;
        }
    }

    /// Test/observability hook: how many servers are currently live.
    pub fn running_server_count(&self) -> usize {
        self.servers.lock().map(|m| m.len()).unwrap_or(0)
    }
}

/// The [`crate::tools::WriteObserver`] `[capabilities.lsp]` installs —
/// `before_write` is a true no-op (LSP has nothing to capture before a
/// mutation); `after_write` delegates straight to
/// [`LspManager::diagnostics_after_write`].
#[derive(Debug)]
pub struct LspDiagnosticsObserver {
    manager: Arc<LspManager>,
}

impl LspDiagnosticsObserver {
    /// Wrap `manager` as a [`crate::tools::WriteObserver`].
    pub fn new(manager: Arc<LspManager>) -> Self {
        LspDiagnosticsObserver { manager }
    }
}

#[async_trait::async_trait]
impl crate::tools::WriteObserver for LspDiagnosticsObserver {
    async fn before_write(&self, _path: &Path) {}
    async fn after_write(&self, path: &Path) -> Option<String> {
        self.manager.diagnostics_after_write(path).await
    }
}

/// Build the [`LspManager`] a fresh [`crate::Agent`] should install, given
/// a resolved [`crate::Config`] — called once, from
/// `crate::agent::build_tool_context`. `Config::lsp_enabled` is the ONE
/// gate: `false` (the default) returns `None` WITHOUT spawning anything —
/// the default-off byte-identity guarantee. `true` with an EMPTY
/// `Config::lsp_servers` still returns a (harmless, does-nothing) manager,
/// but warns once — an enabled module with no configured servers is very
/// likely a config mistake, not silent-by-design.
pub fn manager_for_config(config: &crate::Config) -> Option<Arc<LspManager>> {
    if !config.lsp_enabled {
        return None;
    }
    if config.lsp_servers.is_empty() {
        eprintln!(
            "warning: [capabilities.lsp] is enabled but no servers are configured under \
             [capabilities.lsp.servers.<name>] — no language server will ever be launched"
        );
    }
    Some(Arc::new(LspManager::new(
        config.cwd.clone(),
        config.lsp_servers.clone(),
        Duration::from_secs(config.lsp_timeout_secs.max(1)),
        config.lsp_max_diagnostics.max(1),
    )))
}

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

    /// A tiny, deterministic, harmless stub "language server": a shell
    /// script speaking just enough LSP over stdio to exercise this
    /// module's handshake + diagnostics path — NEVER a real network
    /// download, NEVER a billed model (live-agent-safety, build brief).
    /// Behavior: responds to `initialize` with an empty capabilities
    /// result, ignores `initialized`, and on EVERY `didOpen`/`didChange`
    /// publishes ONE fixed diagnostic (a "found the word TODO" style
    /// error) if the document text contains `"TODO"`, else an EMPTY
    /// diagnostics array (a clean file) — deterministic on input content,
    /// so tests can assert both the "diagnostics found" and "clean" paths.
    /// Responds to `shutdown` with a null result.
    const STUB_SERVER_PY: &str = r#"
import sys, json

def read_message():
    headers = {}
    while True:
        line = sys.stdin.buffer.readline()
        if not line:
            return None
        line = line.decode("utf-8", "replace").rstrip("\r\n")
        if line == "":
            break
        if ":" in line:
            k, v = line.split(":", 1)
            headers[k.strip()] = v.strip()
    length = int(headers.get("Content-Length", "0"))
    body = sys.stdin.buffer.read(length)
    return json.loads(body.decode("utf-8"))

def write_message(obj):
    body = json.dumps(obj).encode("utf-8")
    sys.stdout.buffer.write(("Content-Length: %d\r\n\r\n" % len(body)).encode("utf-8"))
    sys.stdout.buffer.write(body)
    sys.stdout.buffer.flush()

def diagnostics_for(text):
    if "TODO" in text:
        return [{
            "range": {"start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 4}},
            "severity": 1,
            "message": "found a TODO marker",
        }]
    return []

while True:
    msg = read_message()
    if msg is None:
        break
    method = msg.get("method")
    if method == "initialize":
        write_message({"jsonrpc": "2.0", "id": msg["id"], "result": {"capabilities": {}}})
    elif method == "initialized":
        pass
    elif method in ("textDocument/didOpen", "textDocument/didChange"):
        params = msg["params"]
        if method == "textDocument/didOpen":
            uri = params["textDocument"]["uri"]
            text = params["textDocument"]["text"]
        else:
            uri = params["textDocument"]["uri"]
            text = params["contentChanges"][0]["text"]
        write_message({
            "jsonrpc": "2.0",
            "method": "textDocument/publishDiagnostics",
            "params": {"uri": uri, "diagnostics": diagnostics_for(text)},
        })
    elif method == "shutdown":
        write_message({"jsonrpc": "2.0", "id": msg["id"], "result": None})
    elif method == "exit":
        break
"#;

    /// A stub server that never responds to ANYTHING — proves the
    /// timeout-bounded degrade path (never a hang).
    const SILENT_SERVER_PY: &str = r#"
import sys, time
while True:
    line = sys.stdin.buffer.readline()
    if not line:
        break
    time.sleep(3600)
"#;

    /// A stub "language server" that — like a REAL configured server
    /// (rust-analyzer's proc-macro/build server, typescript-language-
    /// server's `tsserver`, gopls's `go`) — spawns its OWN persistent
    /// WORKER grandchild the moment it starts, and records that
    /// grandchild's pid to `sys.argv[1]` (a path this test polls). The
    /// worker (`sleep 3600`) is spawned via plain `subprocess.Popen` with
    /// no `start_new_session`, so it inherits THIS process's process group
    /// exactly like a real worker subprocess would — the P5-11 review's
    /// exact repro for "grandchildren orphan on session teardown".
    /// Otherwise behaves like [`STUB_SERVER_PY`] (empty diagnostics on
    /// every write) — this test only cares about process lifecycle, not
    /// diagnostics content.
    const WORKER_STUB_SERVER_PY: &str = r#"
import sys, json, subprocess

def read_message():
    headers = {}
    while True:
        line = sys.stdin.buffer.readline()
        if not line:
            return None
        line = line.decode("utf-8", "replace").rstrip("\r\n")
        if line == "":
            break
        if ":" in line:
            k, v = line.split(":", 1)
            headers[k.strip()] = v.strip()
    length = int(headers.get("Content-Length", "0"))
    body = sys.stdin.buffer.read(length)
    return json.loads(body.decode("utf-8"))

def write_message(obj):
    body = json.dumps(obj).encode("utf-8")
    sys.stdout.buffer.write(("Content-Length: %d\r\n\r\n" % len(body)).encode("utf-8"))
    sys.stdout.buffer.write(body)
    sys.stdout.buffer.flush()

worker = subprocess.Popen(["sleep", "3600"])
with open(sys.argv[1], "w") as f:
    f.write(str(worker.pid))
    f.flush()

while True:
    msg = read_message()
    if msg is None:
        break
    method = msg.get("method")
    if method == "initialize":
        write_message({"jsonrpc": "2.0", "id": msg["id"], "result": {"capabilities": {}}})
    elif method == "initialized":
        pass
    elif method in ("textDocument/didOpen", "textDocument/didChange"):
        uri = msg["params"]["textDocument"]["uri"]
        write_message({
            "jsonrpc": "2.0",
            "method": "textDocument/publishDiagnostics",
            "params": {"uri": uri, "diagnostics": []},
        })
    elif method == "shutdown":
        write_message({"jsonrpc": "2.0", "id": msg["id"], "result": None})
    elif method == "exit":
        break
"#;

    fn write_stub(dir: &Path, name: &str, source: &str) -> PathBuf {
        let path = dir.join(name);
        std::fs::write(&path, source).unwrap();
        path
    }

    fn python() -> Option<String> {
        for candidate in ["python3", "python"] {
            if std::process::Command::new(candidate)
                .arg("--version")
                .output()
                .is_ok()
            {
                return Some(candidate.to_string());
            }
        }
        None
    }

    fn tmp(tag: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "supercode-lsp-test-{tag}-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    fn stub_spec(script: &Path) -> LspServerSpec {
        LspServerSpec {
            command: python().expect("python3/python required for lsp tests"),
            args: vec![script.to_string_lossy().into_owned()],
            extensions: vec![".rs".to_string()],
        }
    }

    #[tokio::test]
    async fn manager_for_config_is_none_when_disabled_default_off_byte_identity() {
        let config = crate::Config::builder().model("m").build();
        assert!(!config.lsp_enabled);
        assert!(manager_for_config(&config).is_none());
    }

    #[tokio::test]
    async fn diagnostics_after_write_surfaces_a_diagnostic_from_the_stub_server() {
        let Some(_py) = python() else {
            eprintln!("skipping: no python3/python on PATH");
            return;
        };
        let project = tmp("diag-hit");
        let script = write_stub(&project, "stub_lsp.py", STUB_SERVER_PY);
        let manager = LspManager::new(
            project.clone(),
            vec![("stub".to_string(), stub_spec(&script))],
            Duration::from_secs(5),
            DEFAULT_LSP_MAX_DIAGNOSTICS,
        );
        let file = project.join("has_todo.rs");
        std::fs::write(&file, "// TODO fix this\nfn main() {}\n").unwrap();
        let result = manager.diagnostics_after_write(&file).await;
        let text = result.expect("expected diagnostics for a file containing TODO");
        assert!(text.contains("stub"), "names the server: {text}");
        assert!(text.contains("found a TODO marker"), "{text}");
        manager.shutdown_all().await;
        std::fs::remove_dir_all(&project).ok();
    }

    #[tokio::test]
    async fn diagnostics_after_write_is_none_for_a_clean_file() {
        let Some(_py) = python() else {
            eprintln!("skipping: no python3/python on PATH");
            return;
        };
        let project = tmp("diag-clean");
        let script = write_stub(&project, "stub_lsp.py", STUB_SERVER_PY);
        let manager = LspManager::new(
            project.clone(),
            vec![("stub".to_string(), stub_spec(&script))],
            Duration::from_secs(5),
            DEFAULT_LSP_MAX_DIAGNOSTICS,
        );
        let file = project.join("clean.rs");
        std::fs::write(&file, "fn main() {}\n").unwrap();
        let result = manager.diagnostics_after_write(&file).await;
        assert!(
            result.is_none(),
            "a clean file must not produce a diagnostics annotation: {result:?}"
        );
        manager.shutdown_all().await;
        std::fs::remove_dir_all(&project).ok();
    }

    #[tokio::test]
    async fn diagnostics_after_write_is_none_for_an_unconfigured_extension() {
        let Some(_py) = python() else {
            eprintln!("skipping: no python3/python on PATH");
            return;
        };
        let project = tmp("diag-unconfigured");
        let script = write_stub(&project, "stub_lsp.py", STUB_SERVER_PY);
        let manager = LspManager::new(
            project.clone(),
            vec![("stub".to_string(), stub_spec(&script))], // only .rs
            Duration::from_secs(5),
            DEFAULT_LSP_MAX_DIAGNOSTICS,
        );
        let file = project.join("has_todo.py");
        std::fs::write(&file, "# TODO\n").unwrap();
        let result = manager.diagnostics_after_write(&file).await;
        assert!(result.is_none());
        assert_eq!(
            manager.running_server_count(),
            0,
            "an unconfigured extension must never spawn anything"
        );
        std::fs::remove_dir_all(&project).ok();
    }

    #[tokio::test]
    async fn a_second_write_to_the_same_server_reuses_the_running_process() {
        let Some(_py) = python() else {
            eprintln!("skipping: no python3/python on PATH");
            return;
        };
        let project = tmp("diag-reuse");
        let script = write_stub(&project, "stub_lsp.py", STUB_SERVER_PY);
        let manager = LspManager::new(
            project.clone(),
            vec![("stub".to_string(), stub_spec(&script))],
            Duration::from_secs(5),
            DEFAULT_LSP_MAX_DIAGNOSTICS,
        );
        let file = project.join("f.rs");
        std::fs::write(&file, "fn main() {}\n").unwrap();
        manager.diagnostics_after_write(&file).await;
        assert_eq!(manager.running_server_count(), 1);
        std::fs::write(&file, "// TODO\nfn main() {}\n").unwrap();
        manager.diagnostics_after_write(&file).await;
        assert_eq!(
            manager.running_server_count(),
            1,
            "a second write to the same extension must REUSE the already-running server, not spawn a second one"
        );
        manager.shutdown_all().await;
        std::fs::remove_dir_all(&project).ok();
    }

    /// Bounded: proves a timeout on a server that never answers degrades
    /// to `None` (never a hang, never a panic, never a failed tool call).
    #[tokio::test]
    async fn a_silent_server_degrades_to_none_within_the_timeout_bound() {
        let Some(_py) = python() else {
            eprintln!("skipping: no python3/python on PATH");
            return;
        };
        let project = tmp("diag-silent");
        let script = write_stub(&project, "silent_lsp.py", SILENT_SERVER_PY);
        let manager = LspManager::new(
            project.clone(),
            vec![("silent".to_string(), stub_spec(&script))],
            Duration::from_millis(500),
            DEFAULT_LSP_MAX_DIAGNOSTICS,
        );
        let file = project.join("f.rs");
        std::fs::write(&file, "fn main() {}\n").unwrap();
        let started = std::time::Instant::now();
        let result = tokio::time::timeout(
            Duration::from_secs(10),
            manager.diagnostics_after_write(&file),
        )
        .await
        .expect("must not hang past the configured lsp timeout");
        assert!(result.is_none());
        assert!(
            started.elapsed() < Duration::from_secs(5),
            "took {:?}, expected to bail out near the 500ms configured timeout",
            started.elapsed()
        );
        manager.kill_all_sync();
        std::fs::remove_dir_all(&project).ok();
    }

    /// No-orphan-LSP proof: after `kill_all_sync` (the same call
    /// `impl Drop for Agent` makes), the spawned OS process must actually
    /// be dead — not merely removed from the manager's bookkeeping.
    #[tokio::test]
    async fn kill_all_sync_actually_terminates_the_os_process() {
        let Some(_py) = python() else {
            eprintln!("skipping: no python3/python on PATH");
            return;
        };
        let project = tmp("diag-kill");
        let script = write_stub(&project, "stub_lsp.py", STUB_SERVER_PY);
        let manager = LspManager::new(
            project.clone(),
            vec![("stub".to_string(), stub_spec(&script))],
            Duration::from_secs(5),
            DEFAULT_LSP_MAX_DIAGNOSTICS,
        );
        let file = project.join("f.rs");
        std::fs::write(&file, "fn main() {}\n").unwrap();
        manager.diagnostics_after_write(&file).await;
        assert_eq!(manager.running_server_count(), 1);

        let pid = {
            let servers = manager.servers.lock().unwrap();
            let client = servers.values().next().unwrap();
            let id = client.child.lock().unwrap().id();
            id
        };
        let pid = pid.expect("spawned child must have a pid before it's reaped");

        manager.kill_all_sync();
        assert_eq!(
            manager.running_server_count(),
            0,
            "kill_all_sync must drain the manager's bookkeeping"
        );

        // Give the OS a moment to actually reap the SIGKILL'd process, then
        // check it is really gone via `kill -0` (signal 0: existence probe,
        // sends nothing) — `ESRCH` means "no such process".
        let mut still_alive = true;
        for _ in 0..50 {
            let alive = unsafe { libc::kill(pid as libc::pid_t, 0) == 0 };
            if !alive {
                still_alive = false;
                break;
            }
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
        assert!(
            !still_alive,
            "pid {pid} must be dead after kill_all_sync (no orphaned language server)"
        );
        std::fs::remove_dir_all(&project).ok();
    }

    /// P5-11 review repro (MEDIUM, "orphaned grandchild processes on
    /// teardown"): a REAL configured server (rust-analyzer, typescript-
    /// language-server, gopls, ...) commonly spawns its OWN persistent
    /// worker subprocess — `.kill_on_drop(true)`/`Child::start_kill` only
    /// ever signal the ONE directly-tracked pid, so that worker orphans on
    /// every session teardown. This proves `kill_all_sync` (the EXACT call
    /// `impl Drop for Agent` makes) kills the WHOLE process group, so the
    /// stub server's `sleep 3600` worker grandchild is reaped too, not just
    /// the stub server itself. Must FAIL on pre-fix code (direct-child-only
    /// kill leaves the grandchild running) and PASS post-fix
    /// (`Command::process_group(0)` at spawn + group-`SIGKILL` in `kill`).
    #[cfg(unix)]
    #[tokio::test]
    async fn kill_all_sync_reaps_grandchild_worker_processes() {
        let Some(py) = python() else {
            eprintln!("skipping: no python3/python on PATH");
            return;
        };
        let project = tmp("diag-grandchild");
        let script = write_stub(&project, "worker_stub_lsp.py", WORKER_STUB_SERVER_PY);
        let pidfile = project.join("worker.pid");
        let spec = LspServerSpec {
            command: py,
            args: vec![
                script.to_string_lossy().into_owned(),
                pidfile.to_string_lossy().into_owned(),
            ],
            extensions: vec![".rs".to_string()],
        };
        let manager = LspManager::new(
            project.clone(),
            vec![("worker".to_string(), spec)],
            Duration::from_secs(5),
            DEFAULT_LSP_MAX_DIAGNOSTICS,
        );
        let file = project.join("f.rs");
        std::fs::write(&file, "fn main() {}\n").unwrap();
        manager.diagnostics_after_write(&file).await;
        assert_eq!(manager.running_server_count(), 1);

        // Wait for the stub to have recorded its worker grandchild's pid.
        let mut grandchild_pid: Option<i32> = None;
        for _ in 0..100 {
            if let Ok(s) = std::fs::read_to_string(&pidfile) {
                if let Ok(pid) = s.trim().parse::<i32>() {
                    grandchild_pid = Some(pid);
                    break;
                }
            }
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
        let grandchild_pid =
            grandchild_pid.expect("stub server must have recorded its worker grandchild's pid");
        assert!(
            unsafe { libc::kill(grandchild_pid, 0) == 0 },
            "grandchild worker pid {grandchild_pid} must be alive before kill_all_sync"
        );

        manager.kill_all_sync(); // the EXACT call `impl Drop for Agent` makes

        let mut still_alive = true;
        for _ in 0..100 {
            let alive = unsafe { libc::kill(grandchild_pid, 0) == 0 };
            if !alive {
                still_alive = false;
                break;
            }
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
        assert!(
            !still_alive,
            "grandchild worker pid {grandchild_pid} must be dead after kill_all_sync — \
             it must not orphan (P5-11 review repro)"
        );
        std::fs::remove_dir_all(&project).ok();
    }

    /// Path-safety: a path outside the manager's root must never reach the
    /// server, even if it happens to have a configured extension.
    #[tokio::test]
    async fn diagnostics_after_write_refuses_a_path_outside_the_root() {
        let Some(_py) = python() else {
            eprintln!("skipping: no python3/python on PATH");
            return;
        };
        let project = tmp("diag-outside-project");
        let outside = tmp("diag-outside-elsewhere");
        let script = write_stub(&project, "stub_lsp.py", STUB_SERVER_PY);
        let manager = LspManager::new(
            project.clone(),
            vec![("stub".to_string(), stub_spec(&script))],
            Duration::from_secs(5),
            DEFAULT_LSP_MAX_DIAGNOSTICS,
        );
        let victim = outside.join("victim.rs");
        std::fs::write(&victim, "// TODO\nfn main() {}\n").unwrap();
        let result = manager.diagnostics_after_write(&victim).await;
        assert!(result.is_none());
        assert_eq!(manager.running_server_count(), 0);
        std::fs::remove_dir_all(&project).ok();
        std::fs::remove_dir_all(&outside).ok();
    }

    #[tokio::test]
    async fn lsp_diagnostics_observer_before_write_is_a_true_noop() {
        let project = tmp("obs-noop");
        let manager = Arc::new(LspManager::new(
            project.clone(),
            vec![],
            Duration::from_secs(5),
            DEFAULT_LSP_MAX_DIAGNOSTICS,
        ));
        let observer = LspDiagnosticsObserver::new(manager);
        // Must not panic/spawn anything for an unconfigured setup.
        <LspDiagnosticsObserver as crate::tools::WriteObserver>::before_write(
            &observer,
            &project.join("f.rs"),
        )
        .await;
        std::fs::remove_dir_all(&project).ok();
    }
}