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
use super::super::{
    CodeDiagnostic, CodeDiagnosticSeverity, CodeLocation, CodePosition, CodeRange, CodeSymbolKind,
    DocumentSymbol, SymbolInformation,
};
use crate::workspace::WorkspacePath;
use lsp_types::{
    Diagnostic, DiagnosticSeverity, DocumentSymbolResponse, GotoDefinitionResponse, Location,
    LocationLink, NumberOrString, OneOf, SymbolKind, Uri, WorkspaceSymbol, WorkspaceSymbolResponse,
};
use std::io;
use std::path::{Path, PathBuf};
use thiserror::Error;
use url::Url;

/// Failure while normalizing a language-server response into core types.
#[derive(Debug, Error)]
pub(crate) enum MappingError {
    #[error("workspace root must be an absolute canonical path: {root:?}")]
    InvalidWorkspaceRoot { root: PathBuf },

    #[error("unsupported resource URI scheme: {scheme}")]
    UnsupportedUriScheme { scheme: String },

    #[error("resource URI is not a valid local file URI: {uri}")]
    InvalidFileUri { uri: String },

    #[error("resource path does not exist: {path:?}")]
    PathDoesNotExist { path: PathBuf },

    #[error("resource path could not be resolved: {path:?}: {source}")]
    PathResolution {
        path: PathBuf,
        #[source]
        source: io::Error,
    },

    #[error("resource path is outside the workspace: {path:?}")]
    OutsideWorkspace { path: PathBuf },

    #[error("workspace-relative resource path is not valid UTF-8: {path:?}")]
    NonUtf8WorkspacePath { path: PathBuf },

    #[error("protocol range ends before it starts: {start:?}..{end:?}")]
    InvalidRange {
        start: CodePosition,
        end: CodePosition,
    },

    #[error("protocol selection range {selection:?} is outside enclosing range {enclosing:?}")]
    SelectionOutsideRange {
        selection: CodeRange,
        enclosing: CodeRange,
    },
}

pub(crate) fn map_position(position: lsp_types::Position) -> CodePosition {
    CodePosition::new(position.line, position.character)
}

pub(crate) fn map_range(range: lsp_types::Range) -> Result<CodeRange, MappingError> {
    let start = map_position(range.start);
    let end = map_position(range.end);
    if end < start {
        return Err(MappingError::InvalidRange { start, end });
    }

    Ok(CodeRange::new(start, end))
}

pub(crate) fn map_document_symbol(
    symbol: lsp_types::DocumentSymbol,
) -> Result<DocumentSymbol, MappingError> {
    let range = map_range(symbol.range)?;
    let selection_range = map_range(symbol.selection_range)?;
    ensure_range_contains(range, selection_range)?;
    let children = symbol
        .children
        .unwrap_or_default()
        .into_iter()
        .map(map_document_symbol)
        .collect::<Result<_, _>>()?;

    Ok(DocumentSymbol {
        name: symbol.name,
        detail: symbol.detail,
        kind: map_symbol_kind(symbol.kind),
        range,
        selection_range,
        children,
    })
}

pub(crate) async fn map_document_symbol_response(
    canonical_workspace_root: &Path,
    response: DocumentSymbolResponse,
) -> Result<Vec<DocumentSymbol>, MappingError> {
    match response {
        DocumentSymbolResponse::Nested(symbols) => symbols
            .into_iter()
            .map(map_document_symbol)
            .collect::<Result<_, _>>(),
        DocumentSymbolResponse::Flat(symbols) => {
            let mut mapped_symbols = Vec::with_capacity(symbols.len());
            for symbol in symbols {
                let mapped = map_symbol_information(canonical_workspace_root, symbol).await?;
                mapped_symbols.push(DocumentSymbol {
                    name: mapped.name,
                    detail: None,
                    kind: mapped.kind,
                    range: mapped.location.range,
                    selection_range: mapped.location.range,
                    children: Vec::new(),
                });
            }
            Ok(mapped_symbols)
        }
    }
}

pub(crate) async fn map_symbol_information(
    canonical_workspace_root: &Path,
    symbol: lsp_types::SymbolInformation,
) -> Result<SymbolInformation, MappingError> {
    Ok(SymbolInformation {
        name: symbol.name,
        kind: map_symbol_kind(symbol.kind),
        location: map_location(canonical_workspace_root, symbol.location).await?,
        container_name: symbol.container_name,
    })
}

pub(crate) async fn map_workspace_symbol(
    canonical_workspace_root: &Path,
    symbol: WorkspaceSymbol,
) -> Result<SymbolInformation, MappingError> {
    let location = match symbol.location {
        OneOf::Left(location) => map_location(canonical_workspace_root, location).await?,
        OneOf::Right(location) => CodeLocation {
            path: file_uri_to_workspace_path(canonical_workspace_root, &location.uri).await?,
            range: CodeRange::default(),
        },
    };

    Ok(SymbolInformation {
        name: symbol.name,
        kind: map_symbol_kind(symbol.kind),
        location,
        container_name: symbol.container_name,
    })
}

pub(crate) async fn map_workspace_symbol_response(
    canonical_workspace_root: &Path,
    response: WorkspaceSymbolResponse,
) -> Result<Vec<SymbolInformation>, MappingError> {
    let mut mapped_symbols = Vec::new();
    match response {
        WorkspaceSymbolResponse::Flat(symbols) => {
            mapped_symbols.reserve(symbols.len());
            for symbol in symbols {
                mapped_symbols
                    .push(map_symbol_information(canonical_workspace_root, symbol).await?);
            }
        }
        WorkspaceSymbolResponse::Nested(symbols) => {
            mapped_symbols.reserve(symbols.len());
            for symbol in symbols {
                mapped_symbols.push(map_workspace_symbol(canonical_workspace_root, symbol).await?);
            }
        }
    }
    Ok(mapped_symbols)
}

pub(crate) async fn map_location(
    canonical_workspace_root: &Path,
    location: Location,
) -> Result<CodeLocation, MappingError> {
    Ok(CodeLocation {
        path: file_uri_to_workspace_path(canonical_workspace_root, &location.uri).await?,
        range: map_range(location.range)?,
    })
}

pub(crate) async fn map_location_link(
    canonical_workspace_root: &Path,
    link: LocationLink,
) -> Result<CodeLocation, MappingError> {
    let target_range = map_range(link.target_range)?;
    let target_selection_range = map_range(link.target_selection_range)?;
    ensure_range_contains(target_range, target_selection_range)?;

    Ok(CodeLocation {
        path: file_uri_to_workspace_path(canonical_workspace_root, &link.target_uri).await?,
        range: target_selection_range,
    })
}

pub(crate) async fn map_definition_response(
    canonical_workspace_root: &Path,
    response: Option<GotoDefinitionResponse>,
) -> Result<Vec<CodeLocation>, MappingError> {
    match response {
        None => Ok(Vec::new()),
        Some(GotoDefinitionResponse::Scalar(location)) => Ok(vec![
            map_location(canonical_workspace_root, location).await?,
        ]),
        Some(GotoDefinitionResponse::Array(locations)) => {
            let mut mapped = Vec::with_capacity(locations.len());
            for location in locations {
                mapped.push(map_location(canonical_workspace_root, location).await?);
            }
            Ok(mapped)
        }
        Some(GotoDefinitionResponse::Link(links)) => {
            let mut mapped = Vec::with_capacity(links.len());
            for link in links {
                mapped.push(map_location_link(canonical_workspace_root, link).await?);
            }
            Ok(mapped)
        }
    }
}

pub(crate) async fn map_diagnostics(
    canonical_workspace_root: &Path,
    uri: &Uri,
    diagnostics: Vec<Diagnostic>,
) -> Result<Vec<CodeDiagnostic>, MappingError> {
    let path = file_uri_to_workspace_path(canonical_workspace_root, uri).await?;
    diagnostics
        .into_iter()
        .map(|diagnostic| {
            Ok(CodeDiagnostic {
                location: CodeLocation {
                    path: path.clone(),
                    range: map_range(diagnostic.range)?,
                },
                severity: diagnostic.severity.and_then(map_diagnostic_severity),
                code: diagnostic.code.map(|code| match code {
                    NumberOrString::Number(number) => number.to_string(),
                    NumberOrString::String(text) => text,
                }),
                source: diagnostic.source,
                message: diagnostic.message,
            })
        })
        .collect()
}

pub(crate) fn map_symbol_kind(kind: SymbolKind) -> CodeSymbolKind {
    match kind {
        SymbolKind::FILE => CodeSymbolKind::File,
        SymbolKind::MODULE => CodeSymbolKind::Module,
        SymbolKind::NAMESPACE => CodeSymbolKind::Namespace,
        SymbolKind::PACKAGE => CodeSymbolKind::Package,
        SymbolKind::CLASS => CodeSymbolKind::Class,
        SymbolKind::METHOD => CodeSymbolKind::Method,
        SymbolKind::PROPERTY => CodeSymbolKind::Property,
        SymbolKind::FIELD => CodeSymbolKind::Field,
        SymbolKind::CONSTRUCTOR => CodeSymbolKind::Constructor,
        SymbolKind::ENUM => CodeSymbolKind::Enum,
        SymbolKind::INTERFACE => CodeSymbolKind::Interface,
        SymbolKind::FUNCTION => CodeSymbolKind::Function,
        SymbolKind::VARIABLE => CodeSymbolKind::Variable,
        SymbolKind::CONSTANT => CodeSymbolKind::Constant,
        SymbolKind::STRING => CodeSymbolKind::String,
        SymbolKind::NUMBER => CodeSymbolKind::Number,
        SymbolKind::BOOLEAN => CodeSymbolKind::Boolean,
        SymbolKind::ARRAY => CodeSymbolKind::Array,
        SymbolKind::OBJECT => CodeSymbolKind::Object,
        SymbolKind::KEY => CodeSymbolKind::Key,
        SymbolKind::NULL => CodeSymbolKind::Null,
        SymbolKind::ENUM_MEMBER => CodeSymbolKind::EnumMember,
        SymbolKind::STRUCT => CodeSymbolKind::Struct,
        SymbolKind::EVENT => CodeSymbolKind::Event,
        SymbolKind::OPERATOR => CodeSymbolKind::Operator,
        SymbolKind::TYPE_PARAMETER => CodeSymbolKind::TypeParameter,
        _ => CodeSymbolKind::Unknown,
    }
}

pub(crate) fn map_diagnostic_severity(
    severity: DiagnosticSeverity,
) -> Option<CodeDiagnosticSeverity> {
    match severity {
        DiagnosticSeverity::ERROR => Some(CodeDiagnosticSeverity::Error),
        DiagnosticSeverity::WARNING => Some(CodeDiagnosticSeverity::Warning),
        DiagnosticSeverity::INFORMATION => Some(CodeDiagnosticSeverity::Information),
        DiagnosticSeverity::HINT => Some(CodeDiagnosticSeverity::Hint),
        _ => None,
    }
}

/// Convert a local file URI into a canonical, workspace-relative path.
///
/// Both the workspace root and the URI target are expected to exist. The root
/// must already be canonical; the target is canonicalized before containment
/// is checked so a symlink cannot escape the workspace. A missing target is an
/// error rather than an invitation to fall back to lexical normalization.
pub(crate) async fn file_uri_to_workspace_path(
    canonical_workspace_root: &Path,
    uri: &Uri,
) -> Result<WorkspacePath, MappingError> {
    if !canonical_workspace_root.is_absolute() {
        return Err(MappingError::InvalidWorkspaceRoot {
            root: canonical_workspace_root.to_path_buf(),
        });
    }

    let uri_text = uri.as_str();
    let parsed = Url::parse(uri_text).map_err(|_| MappingError::InvalidFileUri {
        uri: uri_text.to_owned(),
    })?;
    if parsed.scheme() != "file" {
        return Err(MappingError::UnsupportedUriScheme {
            scheme: parsed.scheme().to_owned(),
        });
    }
    if parsed.query().is_some()
        || parsed.fragment().is_some()
        || !has_valid_percent_encoding(parsed.path())
    {
        return Err(MappingError::InvalidFileUri {
            uri: uri_text.to_owned(),
        });
    }

    let decoded_path = parsed
        .to_file_path()
        .map_err(|()| MappingError::InvalidFileUri {
            uri: uri_text.to_owned(),
        })?;
    let canonical_path = tokio::fs::canonicalize(&decoded_path)
        .await
        .map_err(|source| {
            if source.kind() == io::ErrorKind::NotFound {
                MappingError::PathDoesNotExist {
                    path: decoded_path.clone(),
                }
            } else {
                MappingError::PathResolution {
                    path: decoded_path.clone(),
                    source,
                }
            }
        })?;
    let relative = canonical_path
        .strip_prefix(canonical_workspace_root)
        .map_err(|_| MappingError::OutsideWorkspace {
            path: canonical_path.clone(),
        })?;
    let relative = relative
        .to_str()
        .ok_or_else(|| MappingError::NonUtf8WorkspacePath {
            path: relative.to_path_buf(),
        })?;

    Ok(WorkspacePath::from_normalized(relative))
}

fn ensure_range_contains(enclosing: CodeRange, selection: CodeRange) -> Result<(), MappingError> {
    if selection.start < enclosing.start || selection.end > enclosing.end {
        return Err(MappingError::SelectionOutsideRange {
            selection,
            enclosing,
        });
    }
    Ok(())
}

fn has_valid_percent_encoding(value: &str) -> bool {
    let bytes = value.as_bytes();
    let mut index = 0;
    while index < bytes.len() {
        if bytes[index] != b'%' {
            index += 1;
            continue;
        }

        if index + 2 >= bytes.len()
            || !bytes[index + 1].is_ascii_hexdigit()
            || !bytes[index + 2].is_ascii_hexdigit()
        {
            return false;
        }
        index += 3;
    }
    true
}

#[cfg(test)]
mod tests {
    use super::*;
    use lsp_types::{
        DocumentSymbol as LspDocumentSymbol, Position, Range,
        SymbolInformation as LspSymbolInformation, WorkspaceLocation,
    };
    use serde_json::json;
    use std::fs;
    use tempfile::TempDir;

    fn canonical_root(directory: &TempDir) -> PathBuf {
        fs::canonicalize(directory.path()).unwrap()
    }

    fn create_file(directory: &TempDir, relative: &str) -> PathBuf {
        let path = directory.path().join(relative);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(&path, b"saved content").unwrap();
        path
    }

    fn file_uri(path: &Path) -> Uri {
        Url::from_file_path(path).unwrap().as_str().parse().unwrap()
    }

    fn protocol_range(start: (u32, u32), end: (u32, u32)) -> Range {
        Range::new(Position::new(start.0, start.1), Position::new(end.0, end.1))
    }

    #[allow(deprecated)]
    fn document_symbol(
        name: &str,
        kind: SymbolKind,
        range: Range,
        selection_range: Range,
        children: Vec<LspDocumentSymbol>,
    ) -> LspDocumentSymbol {
        LspDocumentSymbol {
            name: name.to_owned(),
            detail: None,
            kind,
            tags: None,
            deprecated: None,
            range,
            selection_range,
            children: Some(children),
        }
    }

    #[allow(deprecated)]
    fn symbol_information(
        name: &str,
        kind: SymbolKind,
        location: Location,
    ) -> LspSymbolInformation {
        LspSymbolInformation {
            name: name.to_owned(),
            kind,
            tags: None,
            deprecated: None,
            location,
            container_name: Some("container".to_owned()),
        }
    }

    #[test]
    fn position_preserves_utf16_code_unit_offset() {
        let prefix = "a\u{1f980}\u{4e2d}";
        let utf16_offset = prefix.encode_utf16().count() as u32;
        assert_eq!(utf16_offset, 4);

        assert_eq!(
            map_position(Position::new(7, utf16_offset)),
            CodePosition::new(7, 4)
        );
    }

    #[tokio::test]
    async fn document_symbols_keep_nested_structure() {
        let workspace = TempDir::new().unwrap();
        let root = canonical_root(&workspace);
        let child = document_symbol(
            "method",
            SymbolKind::METHOD,
            protocol_range((2, 2), (4, 3)),
            protocol_range((2, 5), (2, 11)),
            Vec::new(),
        );
        let parent = document_symbol(
            "Type",
            SymbolKind::CLASS,
            protocol_range((1, 0), (5, 1)),
            protocol_range((1, 6), (1, 10)),
            vec![child],
        );

        let mapped =
            map_document_symbol_response(&root, DocumentSymbolResponse::Nested(vec![parent]))
                .await
                .unwrap()
                .remove(0);
        assert_eq!(mapped.kind, CodeSymbolKind::Class);
        assert_eq!(mapped.children.len(), 1);
        assert_eq!(mapped.children[0].name, "method");
        assert_eq!(mapped.children[0].kind, CodeSymbolKind::Method);
        assert!(mapped.children[0].children.is_empty());
    }

    #[tokio::test]
    async fn definition_response_maps_location_link_array_and_null_shapes() {
        let workspace = TempDir::new().unwrap();
        let root = canonical_root(&workspace);
        let target = create_file(&workspace, "src/target.rs");
        let uri = file_uri(&target);

        let scalar = map_definition_response(
            &root,
            Some(GotoDefinitionResponse::Scalar(Location::new(
                uri.clone(),
                protocol_range((1, 2), (1, 8)),
            ))),
        )
        .await
        .unwrap();
        assert_eq!(scalar.len(), 1);
        assert_eq!(scalar[0].path.as_str(), "src/target.rs");

        let array = map_definition_response(
            &root,
            Some(GotoDefinitionResponse::Array(vec![Location::new(
                uri.clone(),
                protocol_range((2, 0), (2, 4)),
            )])),
        )
        .await
        .unwrap();
        assert_eq!(array[0].range.start, CodePosition::new(2, 0));

        let links = map_definition_response(
            &root,
            Some(GotoDefinitionResponse::Link(vec![LocationLink {
                origin_selection_range: None,
                target_uri: uri,
                target_range: protocol_range((3, 0), (6, 1)),
                target_selection_range: protocol_range((3, 4), (3, 10)),
            }])),
        )
        .await
        .unwrap();
        assert_eq!(
            links[0].range,
            CodeRange::new(CodePosition::new(3, 4), CodePosition::new(3, 10))
        );

        assert!(map_definition_response(&root, None)
            .await
            .unwrap()
            .is_empty());
    }

    #[tokio::test]
    async fn location_link_rejects_selection_outside_target_range() {
        let workspace = TempDir::new().unwrap();
        let root = canonical_root(&workspace);
        let target = create_file(&workspace, "target.ts");
        let error = map_location_link(
            &root,
            LocationLink {
                origin_selection_range: None,
                target_uri: file_uri(&target),
                target_range: protocol_range((5, 0), (7, 0)),
                target_selection_range: protocol_range((4, 0), (4, 3)),
            },
        )
        .await
        .unwrap_err();

        assert!(matches!(error, MappingError::SelectionOutsideRange { .. }));
    }

    #[test]
    fn rejects_reversed_protocol_range() {
        let error = map_range(protocol_range((4, 1), (3, 9))).unwrap_err();
        assert!(matches!(
            error,
            MappingError::InvalidRange {
                start: CodePosition {
                    line: 4,
                    character: 1
                },
                end: CodePosition {
                    line: 3,
                    character: 9
                }
            }
        ));
    }

    #[tokio::test]
    async fn diagnostics_normalize_numeric_and_string_codes() {
        let workspace = TempDir::new().unwrap();
        let root = canonical_root(&workspace);
        let source = create_file(&workspace, "src/lib.rs");
        let diagnostics = vec![
            Diagnostic::new(
                protocol_range((0, 0), (0, 1)),
                Some(DiagnosticSeverity::ERROR),
                Some(NumberOrString::Number(42)),
                Some("compiler".to_owned()),
                "numeric".to_owned(),
                None,
                None,
            ),
            Diagnostic::new(
                protocol_range((1, 0), (1, 1)),
                Some(DiagnosticSeverity::WARNING),
                Some(NumberOrString::String("E_NAME".to_owned())),
                None,
                "string".to_owned(),
                None,
                None,
            ),
        ];

        let mapped = map_diagnostics(&root, &file_uri(&source), diagnostics)
            .await
            .unwrap();
        assert_eq!(mapped[0].code.as_deref(), Some("42"));
        assert_eq!(mapped[0].severity, Some(CodeDiagnosticSeverity::Error));
        assert_eq!(mapped[1].code.as_deref(), Some("E_NAME"));
        assert_eq!(mapped[1].severity, Some(CodeDiagnosticSeverity::Warning));
    }

    #[test]
    fn symbol_and_severity_mappings_handle_unknown_values() {
        let unknown_kind: SymbolKind = serde_json::from_value(json!(99)).unwrap();
        let unknown_severity: DiagnosticSeverity = serde_json::from_value(json!(99)).unwrap();

        assert_eq!(map_symbol_kind(SymbolKind::STRUCT), CodeSymbolKind::Struct);
        assert_eq!(map_symbol_kind(unknown_kind), CodeSymbolKind::Unknown);
        assert_eq!(
            map_diagnostic_severity(DiagnosticSeverity::HINT),
            Some(CodeDiagnosticSeverity::Hint)
        );
        assert_eq!(map_diagnostic_severity(unknown_severity), None);
    }

    #[tokio::test]
    async fn maps_classic_and_range_less_workspace_symbols() {
        let workspace = TempDir::new().unwrap();
        let root = canonical_root(&workspace);
        let source = create_file(&workspace, "src/main.ts");
        let uri = file_uri(&source);

        let classic = map_workspace_symbol_response(
            &root,
            WorkspaceSymbolResponse::Flat(vec![symbol_information(
                "run",
                SymbolKind::FUNCTION,
                Location::new(uri.clone(), protocol_range((1, 1), (1, 4))),
            )]),
        )
        .await
        .unwrap()
        .remove(0);
        assert_eq!(classic.location.path.as_str(), "src/main.ts");
        assert_eq!(classic.kind, CodeSymbolKind::Function);

        let modern = map_workspace_symbol_response(
            &root,
            WorkspaceSymbolResponse::Nested(vec![
                WorkspaceSymbol {
                    name: "Runner".to_owned(),
                    kind: SymbolKind::CLASS,
                    tags: None,
                    container_name: None,
                    location: OneOf::Left(Location::new(
                        uri.clone(),
                        protocol_range((3, 1), (3, 7)),
                    )),
                    data: None,
                },
                WorkspaceSymbol {
                    name: "State".to_owned(),
                    kind: SymbolKind::INTERFACE,
                    tags: None,
                    container_name: Some("model".to_owned()),
                    location: OneOf::Right(WorkspaceLocation { uri }),
                    data: None,
                },
            ]),
        )
        .await
        .unwrap();
        assert_eq!(modern[0].location.range.start, CodePosition::new(3, 1));
        assert_eq!(modern[1].location.path.as_str(), "src/main.ts");
        assert_eq!(modern[1].location.range, CodeRange::default());
    }

    #[tokio::test]
    async fn percent_decodes_file_name() {
        let workspace = TempDir::new().unwrap();
        let root = canonical_root(&workspace);
        let source = create_file(&workspace, "src/with space.rs");
        let uri = file_uri(&source);
        assert!(uri.as_str().contains("with%20space.rs"));

        let mapped = file_uri_to_workspace_path(&root, &uri).await.unwrap();
        assert_eq!(mapped.as_str(), "src/with space.rs");
    }

    #[tokio::test]
    async fn rejects_paths_outside_workspace() {
        let workspace = TempDir::new().unwrap();
        let outside = TempDir::new().unwrap();
        let root = canonical_root(&workspace);
        let source = create_file(&outside, "outside.rs");

        let error = file_uri_to_workspace_path(&root, &file_uri(&source))
            .await
            .unwrap_err();
        assert!(matches!(error, MappingError::OutsideWorkspace { .. }));
    }

    #[tokio::test]
    async fn rejects_non_file_uri() {
        let workspace = TempDir::new().unwrap();
        let root = canonical_root(&workspace);
        let uri: Uri = "https://example.test/source.rs".parse().unwrap();

        let error = file_uri_to_workspace_path(&root, &uri).await.unwrap_err();
        assert!(matches!(
            error,
            MappingError::UnsupportedUriScheme { ref scheme } if scheme == "https"
        ));
    }

    #[tokio::test]
    async fn missing_paths_do_not_use_lexical_fallback() {
        let workspace = TempDir::new().unwrap();
        let root = canonical_root(&workspace);
        let missing = workspace.path().join("missing.rs");

        let error = file_uri_to_workspace_path(&root, &file_uri(&missing))
            .await
            .unwrap_err();
        assert!(matches!(error, MappingError::PathDoesNotExist { .. }));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn rejects_symlink_escape() {
        use std::os::unix::fs::symlink;

        let workspace = TempDir::new().unwrap();
        let outside = TempDir::new().unwrap();
        let root = canonical_root(&workspace);
        let outside_source = create_file(&outside, "secret.rs");
        let linked_source = workspace.path().join("linked.rs");
        symlink(outside_source, &linked_source).unwrap();

        let error = file_uri_to_workspace_path(&root, &file_uri(&linked_source))
            .await
            .unwrap_err();
        assert!(matches!(error, MappingError::OutsideWorkspace { .. }));
    }
}