a3s-code-core 5.3.2

A3S Code Core - Embeddable AI agent library with tool execution
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
//! One lazily-started semantic runtime generation for a workspace layout.

#[cfg(test)]
mod integration_tests;
mod support;
#[cfg(test)]
mod tests;

use support::*;

use std::{
    path::Path,
    sync::{
        atomic::{AtomicBool, AtomicU64, Ordering},
        Arc,
    },
    time::{Duration, Instant},
};

use futures::{stream::FuturesUnordered, StreamExt};
use tokio::sync::{watch, Mutex, RwLock};
use tokio_util::sync::CancellationToken;

use super::{
    diagnostics::DiagnosticsStore,
    document_store::DocumentStore,
    language_profile::LanguageServerProfile,
    language_runtime::{LanguageRuntime, LanguageRuntimeError},
    project_layout::{ProjectLanguageProfile, ProjectLayout},
    CodeDiagnostic, CodeIntelligenceCapabilities, CodeIntelligenceError,
    CodeIntelligenceLanguageStatus, CodeIntelligenceResult, CodeIntelligenceState,
    CodeIntelligenceStatus, CodeLocation, CodePosition, CodeQueryResult, DocumentSymbol,
    NavigationKind, SymbolInformation,
};
use crate::workspace::{
    LocalWorkspaceManifestSnapshot, WorkspaceFileChange, WorkspaceFileSystem, WorkspacePath,
};

const DOCUMENT_CAPACITY: usize = 256;
const DIAGNOSTICS_CAPACITY: usize = 512;
const WORKSPACE_DIAGNOSTIC_LIMIT: usize = 2_000;
const WORKSPACE_DIAGNOSTIC_DOCUMENT_LIMIT: usize = 128;
const WORKSPACE_DIAGNOSTIC_CONCURRENCY: usize = 8;
const MAX_SYMBOL_LIMIT: usize = 1_000;
const START_RETRY_DELAY: Duration = Duration::from_secs(2);

struct StartFailure {
    at: Instant,
    message: String,
}

enum SlotState {
    Dormant,
    Ready(Arc<LanguageRuntime>),
    Failed(StartFailure),
}

struct LanguageSlot {
    profile: LanguageServerProfile,
    relevant: AtomicBool,
    documents: Arc<DocumentStore>,
    state: Arc<Mutex<SlotState>>,
}

impl LanguageSlot {
    fn new(profile: LanguageServerProfile, relevant: bool, document_capacity: usize) -> Self {
        Self {
            profile,
            relevant: AtomicBool::new(relevant),
            documents: Arc::new(DocumentStore::new(document_capacity)),
            state: Arc::new(Mutex::new(SlotState::Dormant)),
        }
    }
}

/// Runtime processes and saved-document state for one stable layout hash.
pub(crate) struct WorkspaceRuntime {
    canonical_root: std::path::PathBuf,
    layout: ProjectLayout,
    file_system: Arc<dyn WorkspaceFileSystem>,
    diagnostics: Arc<DiagnosticsStore>,
    slots: Vec<LanguageSlot>,
    source_paths: RwLock<Vec<WorkspacePath>>,
    workspace_revision: AtomicU64,
    timeout: Duration,
    status: watch::Sender<CodeIntelligenceStatus>,
    shutting_down: AtomicBool,
    lifetime: CancellationToken,
}

impl std::fmt::Debug for WorkspaceRuntime {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("WorkspaceRuntime")
            .field("canonical_root", &self.canonical_root)
            .field("layout_hash", &self.layout.layout_hash)
            .field("workspace_revision", &self.workspace_revision())
            .field("language_slots", &self.slots.len())
            .finish_non_exhaustive()
    }
}

impl Drop for WorkspaceRuntime {
    fn drop(&mut self) {
        // Registry owners normally call `shutdown`, but a host can be dropped
        // during runtime teardown when awaiting is no longer possible. Wake
        // every process monitor so its final Arc is released and
        // `LanguageRuntime::drop` can terminate the child process.
        self.lifetime.cancel();
    }
}

impl WorkspaceRuntime {
    pub(crate) fn new(
        canonical_root: std::path::PathBuf,
        layout: ProjectLayout,
        snapshot: &LocalWorkspaceManifestSnapshot,
        file_system: Arc<dyn WorkspaceFileSystem>,
        timeout: Duration,
    ) -> Self {
        let profiles = LanguageServerProfile::built_in_defaults();
        Self::new_with_profile_set(
            canonical_root,
            layout,
            snapshot,
            file_system,
            timeout,
            profiles,
            DOCUMENT_CAPACITY,
        )
    }

    #[cfg(test)]
    pub(crate) fn new_with_profiles(
        canonical_root: std::path::PathBuf,
        layout: ProjectLayout,
        snapshot: &LocalWorkspaceManifestSnapshot,
        file_system: Arc<dyn WorkspaceFileSystem>,
        timeout: Duration,
        profiles: Vec<LanguageServerProfile>,
    ) -> Self {
        Self::new_with_profile_set(
            canonical_root,
            layout,
            snapshot,
            file_system,
            timeout,
            profiles,
            DOCUMENT_CAPACITY,
        )
    }

    #[cfg(test)]
    pub(crate) fn new_with_profiles_and_document_capacity(
        canonical_root: std::path::PathBuf,
        layout: ProjectLayout,
        snapshot: &LocalWorkspaceManifestSnapshot,
        file_system: Arc<dyn WorkspaceFileSystem>,
        timeout: Duration,
        profiles: Vec<LanguageServerProfile>,
        document_capacity: usize,
    ) -> Self {
        Self::new_with_profile_set(
            canonical_root,
            layout,
            snapshot,
            file_system,
            timeout,
            profiles,
            document_capacity,
        )
    }

    fn new_with_profile_set(
        canonical_root: std::path::PathBuf,
        layout: ProjectLayout,
        snapshot: &LocalWorkspaceManifestSnapshot,
        file_system: Arc<dyn WorkspaceFileSystem>,
        timeout: Duration,
        profiles: Vec<LanguageServerProfile>,
        document_capacity: usize,
    ) -> Self {
        let source_paths = supported_source_paths(snapshot, |path| {
            profiles.iter().any(|profile| profile.supports_path(path))
        });
        let slots = profiles
            .into_iter()
            .map(|profile| {
                let relevant = source_paths
                    .iter()
                    .any(|path| profile.supports_path(Path::new(path.as_str())));
                LanguageSlot::new(profile, relevant, document_capacity)
            })
            .collect();
        let (status, _) = watch::channel(CodeIntelligenceStatus {
            state: CodeIntelligenceState::Starting,
            message: Some("Code Intelligence starts language runtimes on demand".to_owned()),
            ..CodeIntelligenceStatus::default()
        });
        Self {
            canonical_root,
            workspace_revision: AtomicU64::new(snapshot.version),
            layout,
            file_system,
            diagnostics: Arc::new(DiagnosticsStore::new(DIAGNOSTICS_CAPACITY)),
            slots,
            source_paths: RwLock::new(source_paths),
            timeout,
            status,
            shutting_down: AtomicBool::new(false),
            lifetime: CancellationToken::new(),
        }
    }

    pub(crate) fn layout_hash(&self) -> u64 {
        self.layout.layout_hash
    }

    pub(crate) fn subscribe_status(&self) -> watch::Receiver<CodeIntelligenceStatus> {
        self.status.subscribe()
    }

    pub(crate) async fn update_snapshot(&self, snapshot: &LocalWorkspaceManifestSnapshot) {
        let source_paths = supported_source_paths(snapshot, |path| {
            self.slots
                .iter()
                .any(|slot| slot.profile.supports_path(path))
        });
        self.workspace_revision
            .store(snapshot.version, Ordering::Release);
        *self.source_paths.write().await = source_paths.clone();
        for slot in &self.slots {
            let relevant = source_paths
                .iter()
                .any(|path| slot.profile.supports_path(Path::new(path.as_str())));
            let was_relevant = slot.relevant.swap(relevant, Ordering::AcqRel);
            if was_relevant && !relevant {
                let runtime = {
                    let mut state = slot.state.lock().await;
                    match std::mem::replace(&mut *state, SlotState::Dormant) {
                        SlotState::Ready(runtime) => Some(runtime),
                        SlotState::Dormant | SlotState::Failed(_) => None,
                    }
                };
                if let Some(runtime) = runtime {
                    if let Err(error) = runtime.shutdown().await {
                        tracing::warn!(
                            language = %profile_language(slot.profile.id()),
                            error = %error,
                            "Code Intelligence could not stop an irrelevant language runtime"
                        );
                    }
                }
            }
        }
        self.refresh_status().await;
    }

    pub(crate) async fn document_symbols(
        &self,
        path: &WorkspacePath,
        cancellation: CancellationToken,
    ) -> CodeIntelligenceResult<CodeQueryResult<DocumentSymbol>> {
        let content = self.read_saved(path, &cancellation).await?;
        let (profile, runtime) = self.runtime_for_path(path, &cancellation).await?;
        let mut result = runtime
            .document_symbols(path, &content, cancellation.clone())
            .await
            .map_err(|error| map_language_error(profile, error))?;
        self.complete_saved_query(path, &cancellation, &mut result)
            .await?;
        result.workspace_revision = self.workspace_revision();
        Ok(result)
    }

    pub(crate) async fn search_symbols(
        &self,
        query: &str,
        limit: usize,
        cancellation: CancellationToken,
    ) -> CodeIntelligenceResult<CodeQueryResult<SymbolInformation>> {
        if cancellation.is_cancelled() {
            return Err(CodeIntelligenceError::Cancelled);
        }
        let limit = limit.min(MAX_SYMBOL_LIMIT);
        if limit == 0 {
            return Ok(self.workspace_result(Vec::new(), false));
        }

        let mut queries = FuturesUnordered::new();
        for slot in self
            .slots
            .iter()
            .filter(|slot| slot.relevant.load(Ordering::Acquire))
        {
            let cancellation = cancellation.clone();
            queries.push(async move {
                let runtime = self.ensure_runtime(slot, &cancellation).await?;
                runtime
                    .search_symbols(query, limit, cancellation)
                    .await
                    .map_err(|error| map_language_error(slot.profile.id(), error))
            });
        }

        if queries.is_empty() {
            return Err(CodeIntelligenceError::Unavailable {
                message: "no supported saved source files were found in this workspace".to_owned(),
            });
        }

        let mut items = Vec::new();
        let mut truncated = false;
        let mut first_error = None;
        let mut succeeded = false;
        while let Some(result) = queries.next().await {
            match result {
                Ok(result) => {
                    succeeded = true;
                    truncated |= result.truncated;
                    items.extend(result.items);
                }
                Err(CodeIntelligenceError::Cancelled) => {
                    return Err(CodeIntelligenceError::Cancelled)
                }
                Err(error) => {
                    first_error.get_or_insert(error);
                }
            };
        }
        if !succeeded {
            return Err(
                first_error.unwrap_or_else(|| CodeIntelligenceError::Unavailable {
                    message: "no language runtime could search workspace symbols".to_owned(),
                }),
            );
        }

        items.sort_by_cached_key(symbol_key);
        items.dedup_by(|left, right| symbol_key(left) == symbol_key(right));
        truncated |= items.len() > limit;
        items.truncate(limit);
        Ok(self.workspace_result(items, truncated))
    }

    pub(crate) async fn navigate(
        &self,
        kind: NavigationKind,
        path: &WorkspacePath,
        position: CodePosition,
        cancellation: CancellationToken,
    ) -> CodeIntelligenceResult<CodeQueryResult<CodeLocation>> {
        let content = self.read_saved(path, &cancellation).await?;
        let (profile, runtime) = self.runtime_for_path(path, &cancellation).await?;
        let mut result = runtime
            .navigate(kind, path, position, &content, cancellation.clone())
            .await
            .map_err(|error| map_language_error(profile, error))?;
        self.complete_saved_query(path, &cancellation, &mut result)
            .await?;
        result.workspace_revision = self.workspace_revision();
        Ok(result)
    }

    pub(crate) async fn diagnostics(
        &self,
        path: Option<&WorkspacePath>,
        cancellation: CancellationToken,
    ) -> CodeIntelligenceResult<CodeQueryResult<CodeDiagnostic>> {
        let Some(path) = path else {
            return self.workspace_diagnostics(cancellation).await;
        };

        let content = self.read_saved(path, &cancellation).await?;
        let (profile, runtime) = self.runtime_for_path(path, &cancellation).await?;
        let mut result = runtime
            .diagnostics(path, &content, cancellation.clone())
            .await
            .map_err(|error| map_language_error(profile, error))?;
        self.complete_saved_query(path, &cancellation, &mut result)
            .await?;
        result.workspace_revision = self.workspace_revision();
        Ok(result)
    }

    async fn workspace_diagnostics(
        &self,
        cancellation: CancellationToken,
    ) -> CodeIntelligenceResult<CodeQueryResult<CodeDiagnostic>> {
        if cancellation.is_cancelled() {
            return Err(CodeIntelligenceError::Cancelled);
        }
        let source_paths = tokio::select! {
            _ = cancellation.cancelled() => return Err(CodeIntelligenceError::Cancelled),
            paths = self.source_paths.read() => paths.clone(),
        };
        let relevant_slots = self
            .slots
            .iter()
            .enumerate()
            .filter(|(_, slot)| slot.relevant.load(Ordering::Acquire))
            .collect::<Vec<_>>();
        if relevant_slots.is_empty() {
            return Err(CodeIntelligenceError::Unavailable {
                message: "no supported saved source files were found in this workspace".to_owned(),
            });
        }

        // Start each relevant profile independently so one missing executable
        // cannot prevent diagnostics from another language.
        let mut starts = FuturesUnordered::new();
        for (slot_index, slot) in relevant_slots {
            let cancellation = cancellation.clone();
            starts
                .push(async move { (slot_index, self.ensure_runtime(slot, &cancellation).await) });
        }
        let mut runtimes = vec![None; self.slots.len()];
        let mut first_error = None;
        let mut truncated = false;
        while let Some((slot_index, result)) = starts.next().await {
            match result {
                Ok(runtime) => runtimes[slot_index] = Some(runtime),
                Err(CodeIntelligenceError::Cancelled) => {
                    return Err(CodeIntelligenceError::Cancelled)
                }
                Err(error) => {
                    truncated = true;
                    first_error.get_or_insert(error);
                }
            }
        }

        let mut diagnostic_slots = Vec::new();
        for (slot_index, runtime) in runtimes.iter().enumerate() {
            let Some(runtime) = runtime else {
                continue;
            };
            if runtime.capabilities().diagnostics {
                diagnostic_slots.push(slot_index);
            } else {
                truncated = true;
                first_error.get_or_insert_with(|| {
                    map_language_error(
                        self.slots[slot_index].profile.id(),
                        LanguageRuntimeError::Unsupported {
                            operation: "diagnostics",
                        },
                    )
                });
            }
        }
        if diagnostic_slots.is_empty() {
            return Err(
                first_error.unwrap_or_else(|| CodeIntelligenceError::Unavailable {
                    message: "no language runtime can provide workspace diagnostics".to_owned(),
                }),
            );
        }

        let (documents, selection_truncated) = select_workspace_diagnostic_paths(
            &self.slots,
            &diagnostic_slots,
            &source_paths,
            WORKSPACE_DIAGNOSTIC_DOCUMENT_LIMIT,
        );
        truncated |= selection_truncated;
        if documents.is_empty() {
            return Err(
                first_error.unwrap_or_else(|| CodeIntelligenceError::Unavailable {
                    message: "no supported saved source files could be queried".to_owned(),
                }),
            );
        }

        let mut diagnostic_documents = Vec::with_capacity(documents.len());
        for (slot_index, path) in documents {
            let Some(runtime) = runtimes[slot_index].as_ref() else {
                truncated = true;
                first_error.get_or_insert_with(|| CodeIntelligenceError::Unavailable {
                    message: format!(
                        "the {} language runtime became unavailable before diagnostics",
                        profile_language(self.slots[slot_index].profile.id())
                    ),
                });
                continue;
            };
            diagnostic_documents.push((
                self.slots[slot_index].profile.id(),
                Arc::clone(runtime),
                path,
            ));
        }
        if diagnostic_documents.is_empty() {
            return Err(
                first_error.unwrap_or_else(|| CodeIntelligenceError::Unavailable {
                    message: "no language runtime remained available for diagnostics".to_owned(),
                }),
            );
        }

        let queries = diagnostic_documents
            .into_iter()
            .map(|(profile, runtime, path)| {
                let cancellation = cancellation.clone();
                async move {
                    let content = self.read_saved(&path, &cancellation).await?;
                    runtime
                        .diagnostics(&path, &content, cancellation)
                        .await
                        .map_err(|error| map_language_error(profile, error))
                }
            });
        let mut queries =
            futures::stream::iter(queries).buffer_unordered(WORKSPACE_DIAGNOSTIC_CONCURRENCY);
        let mut items = Vec::new();
        let mut succeeded = 0_usize;
        while let Some(result) = queries.next().await {
            match result {
                Ok(result) => {
                    succeeded += 1;
                    truncated |= result.truncated;
                    truncated |=
                        append_bounded(&mut items, result.items, WORKSPACE_DIAGNOSTIC_LIMIT);
                }
                Err(CodeIntelligenceError::Cancelled) => {
                    return Err(CodeIntelligenceError::Cancelled)
                }
                Err(error) => {
                    truncated = true;
                    first_error.get_or_insert(error);
                }
            }
        }
        if succeeded == 0 {
            return Err(
                first_error.unwrap_or_else(|| CodeIntelligenceError::Unavailable {
                    message: "no saved source document returned diagnostics".to_owned(),
                }),
            );
        }

        items.sort_by(diagnostic_order);
        Ok(self.workspace_result(items, truncated))
    }

    pub(crate) async fn notify_file_changes(&self, changes: &[WorkspaceFileChange]) {
        let runtimes = self.ready_runtimes().await;
        for runtime in runtimes {
            if let Err(error) = runtime.notify_file_changes(changes).await {
                tracing::warn!(error = %error, "Code Intelligence file-change notification failed");
            }
        }
    }

    pub(crate) async fn shutdown(&self) {
        if self.shutting_down.swap(true, Ordering::AcqRel) {
            return;
        }
        self.lifetime.cancel();
        let runtimes = self.ready_runtimes().await;
        for runtime in runtimes {
            if let Err(error) = runtime.shutdown().await {
                tracing::warn!(error = %error, "Code Intelligence runtime shutdown failed");
            }
        }
        self.status.send_replace(CodeIntelligenceStatus {
            state: CodeIntelligenceState::Unavailable,
            message: Some("Code Intelligence runtime is shut down".to_owned()),
            ..CodeIntelligenceStatus::default()
        });
    }

    async fn runtime_for_path(
        &self,
        path: &WorkspacePath,
        cancellation: &CancellationToken,
    ) -> CodeIntelligenceResult<(ProjectLanguageProfile, Arc<LanguageRuntime>)> {
        let slot = self
            .slots
            .iter()
            .find(|slot| slot.profile.supports_path(Path::new(path.as_str())))
            .ok_or_else(|| CodeIntelligenceError::Unsupported {
                operation: "language".to_owned(),
                message: format!(
                    "no language profile supports saved document {}",
                    path.as_str()
                ),
            })?;
        slot.relevant.store(true, Ordering::Release);
        let runtime = self.ensure_runtime(slot, cancellation).await?;
        Ok((slot.profile.id(), runtime))
    }

    async fn ensure_runtime(
        &self,
        slot: &LanguageSlot,
        cancellation: &CancellationToken,
    ) -> CodeIntelligenceResult<Arc<LanguageRuntime>> {
        if self.shutting_down.load(Ordering::Acquire) {
            return Err(CodeIntelligenceError::Unavailable {
                message: "the workspace runtime is shutting down".to_owned(),
            });
        }
        let mut state = tokio::select! {
            _ = cancellation.cancelled() => return Err(CodeIntelligenceError::Cancelled),
            state = slot.state.lock() => state,
        };
        let retiring = match &*state {
            SlotState::Ready(runtime) => {
                if let Some(message) = runtime.unavailable_message() {
                    Some((Arc::clone(runtime), message))
                } else {
                    return Ok(Arc::clone(runtime));
                }
            }
            SlotState::Failed(failure) if failure.at.elapsed() < START_RETRY_DELAY => {
                return Err(CodeIntelligenceError::Unavailable {
                    message: failure.message.clone(),
                });
            }
            SlotState::Dormant | SlotState::Failed(_) => None,
        };
        if let Some((runtime, message)) = retiring {
            tracing::warn!(
                language = %profile_language(slot.profile.id()),
                message,
                "Code Intelligence will restart an exited language runtime"
            );
            // The client can observe protocol EOF before the process monitor
            // has reaped a server that kept running. Keep the slot locked and
            // finish the old generation before making it startable again.
            if let Err(error) = runtime.shutdown().await {
                tracing::warn!(
                    language = %profile_language(slot.profile.id()),
                    error = %error,
                    "Code Intelligence could not fully retire an exited language runtime"
                );
                // Keep the failed generation in Ready. A later query may retry
                // cleanup, but no replacement may start while the old process
                // has not been confirmed reaped.
                return Err(map_language_error(slot.profile.id(), error));
            }
            *state = SlotState::Dormant;
        }
        if cancellation.is_cancelled() {
            return Err(CodeIntelligenceError::Cancelled);
        }
        if self.shutting_down.load(Ordering::Acquire) {
            return Err(CodeIntelligenceError::Unavailable {
                message: "the workspace runtime is shutting down".to_owned(),
            });
        }

        let result = LanguageRuntime::start(
            slot.profile.clone(),
            self.canonical_root.clone(),
            self.layout.clone(),
            Arc::clone(&slot.documents),
            Arc::clone(&self.diagnostics),
            cancellation.clone(),
            self.timeout,
        )
        .await;
        if cancellation.is_cancelled() || self.shutting_down.load(Ordering::Acquire) {
            if let Ok(runtime) = result {
                if let Err(error) = runtime.shutdown().await {
                    tracing::warn!(
                        language = %profile_language(slot.profile.id()),
                        error = %error,
                        "Code Intelligence could not retire a cancelled language runtime start"
                    );
                }
            }
            *state = SlotState::Dormant;
            return if cancellation.is_cancelled() {
                Err(CodeIntelligenceError::Cancelled)
            } else {
                Err(CodeIntelligenceError::Unavailable {
                    message: "the workspace runtime is shutting down".to_owned(),
                })
            };
        }
        match result {
            Ok(runtime) => {
                let runtime = Arc::new(runtime);
                *state = SlotState::Ready(Arc::clone(&runtime));
                drop(state);
                self.spawn_runtime_monitor(slot, Arc::clone(&runtime));
                self.refresh_status().await;
                Ok(runtime)
            }
            Err(error) => {
                let message = error.to_string();
                let public = map_language_error(slot.profile.id(), error);
                *state = SlotState::Failed(StartFailure {
                    at: Instant::now(),
                    message,
                });
                drop(state);
                self.refresh_status().await;
                Err(public)
            }
        }
    }

    fn spawn_runtime_monitor(&self, slot: &LanguageSlot, runtime: Arc<LanguageRuntime>) {
        let state = Arc::clone(&slot.state);
        let status = self.status.clone();
        let lifetime = self.lifetime.clone();
        let language = profile_language(slot.profile.id());
        let mut process_state = runtime.subscribe_process_state();
        tokio::spawn(async move {
            loop {
                if !matches!(
                    *process_state.borrow(),
                    super::lsp::process::LspProcessState::Running
                ) {
                    break;
                }
                tokio::select! {
                    _ = lifetime.cancelled() => return,
                    changed = process_state.changed() => {
                        if changed.is_err() {
                            break;
                        }
                    }
                }
            }
            if lifetime.is_cancelled() {
                return;
            }
            let message = runtime
                .unavailable_message()
                .unwrap_or_else(|| "the language runtime stopped unexpectedly".to_owned());
            let mut slot_state = state.lock().await;
            let is_current = matches!(
                &*slot_state,
                SlotState::Ready(current) if Arc::ptr_eq(current, &runtime)
            );
            if !is_current {
                return;
            }
            if let Err(error) = runtime.shutdown().await {
                tracing::warn!(
                    language = %language,
                    error = %error,
                    "Code Intelligence could not clean up a stopped language runtime"
                );
                // Leave the current generation installed. `ensure_runtime`
                // will retry its cleanup and must not start a replacement
                // until shutdown confirms the process has been reaped.
                drop(slot_state);
                publish_stopped_language_status(
                    &status,
                    language,
                    format!("{message}; cleanup failed: {error}"),
                );
                return;
            }
            *slot_state = SlotState::Dormant;
            drop(slot_state);
            publish_stopped_language_status(&status, language, message);
        });
    }

    async fn read_saved(
        &self,
        path: &WorkspacePath,
        cancellation: &CancellationToken,
    ) -> CodeIntelligenceResult<String> {
        let read = self.file_system.read_text(path);
        tokio::select! {
            _ = cancellation.cancelled() => Err(CodeIntelligenceError::Cancelled),
            result = tokio::time::timeout(self.timeout, read) => match result {
                Ok(Ok(content)) => Ok(content),
                Ok(Err(error)) => Err(map_workspace_error(path, error)),
                Err(_) => Err(CodeIntelligenceError::Timeout {
                    operation: "read_saved_document".to_owned(),
                    duration: self.timeout,
                }),
            }
        }
    }

    /// Confirm that the saved bytes which produced a semantic result are
    /// still current. File watchers are intentionally not part of this check:
    /// their delivery may lag behind a query that overlaps an external save.
    async fn complete_saved_query<T>(
        &self,
        path: &WorkspacePath,
        cancellation: &CancellationToken,
        result: &mut CodeQueryResult<T>,
    ) -> CodeIntelligenceResult<()> {
        let Some(snapshot) = result.document.as_mut() else {
            return Ok(());
        };
        match self.read_saved(path, cancellation).await {
            Ok(content) => {
                snapshot.stale |= sha256::digest(content.as_bytes()) != snapshot.content_hash;
                Ok(())
            }
            Err(CodeIntelligenceError::Cancelled) => Err(CodeIntelligenceError::Cancelled),
            Err(_) => {
                // A result based on a file that disappeared or became
                // unreadable during the request is still useful, but cannot
                // be presented as current.
                snapshot.stale = true;
                Ok(())
            }
        }
    }

    async fn ready_runtimes(&self) -> Vec<Arc<LanguageRuntime>> {
        let mut runtimes = Vec::new();
        for slot in &self.slots {
            if let SlotState::Ready(runtime) = &*slot.state.lock().await {
                runtimes.push(Arc::clone(runtime));
            }
        }
        runtimes
    }

    async fn refresh_status(&self) {
        let mut languages = Vec::new();
        let mut capabilities = CodeIntelligenceCapabilities::default();
        let mut ready = 0_usize;
        let mut failed = 0_usize;
        let mut dormant = 0_usize;
        for slot in &self.slots {
            if !slot.relevant.load(Ordering::Acquire) {
                continue;
            }
            let state = slot.state.lock().await;
            let (runtime_state, runtime_capabilities, message) = match &*state {
                SlotState::Dormant => {
                    dormant += 1;
                    (
                        CodeIntelligenceState::Starting,
                        CodeIntelligenceCapabilities::default(),
                        Some("starts on first semantic query".to_owned()),
                    )
                }
                SlotState::Ready(runtime) => {
                    ready += 1;
                    let current = runtime.capabilities();
                    union_capabilities(&mut capabilities, current);
                    (CodeIntelligenceState::Ready, current, None)
                }
                SlotState::Failed(failure) => {
                    failed += 1;
                    (
                        CodeIntelligenceState::Unavailable,
                        CodeIntelligenceCapabilities::default(),
                        Some(failure.message.clone()),
                    )
                }
            };
            languages.push(CodeIntelligenceLanguageStatus {
                language: profile_language(slot.profile.id()),
                state: runtime_state,
                capabilities: runtime_capabilities,
                message,
            });
        }
        let state = if ready > 0 && failed > 0 {
            CodeIntelligenceState::Degraded
        } else if ready > 0 {
            CodeIntelligenceState::Ready
        } else if failed > 0 && dormant == 0 {
            CodeIntelligenceState::Unavailable
        } else if dormant > 0 {
            CodeIntelligenceState::Starting
        } else {
            CodeIntelligenceState::Unavailable
        };
        self.status.send_replace(CodeIntelligenceStatus {
            state,
            capabilities,
            languages,
            message: (failed > 0)
                .then(|| "one or more language runtimes are unavailable".to_owned()),
        });
    }

    fn workspace_revision(&self) -> u64 {
        self.workspace_revision.load(Ordering::Acquire)
    }

    fn workspace_result<T>(&self, items: Vec<T>, truncated: bool) -> CodeQueryResult<T> {
        CodeQueryResult {
            items,
            truncated,
            workspace_revision: self.workspace_revision(),
            document: None,
        }
    }
}