omena-lsp-server 0.4.0

Rust LSP server boundary scaffold for Omena CSS Modules
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
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
use super::*;

#[test]
fn resolves_sass_definition_with_configured_package_manifest_path() -> TestResult {
    let root = std::env::temp_dir().join(format!(
        "omena_lsp_package_manifest_setting_{}_{}",
        std::process::id(),
        current_time_millis()
    ));
    let source = root.join("src/App.module.scss");
    let package_root = root.join("node_modules/@design/tokens");
    let override_style = package_root.join("override.scss");
    let override_manifest = package_root.join("package.lsp.json");
    fs::create_dir_all(fixture_parent(source.as_path(), "source parent")?)?;
    fs::create_dir_all(package_root.as_path())?;
    let source_text = r#"@use "pkg:@design/tokens" as tokens;
.button { color: tokens.$brand; }
"#;
    fs::write(source.as_path(), source_text)?;
    fs::write(override_style.as_path(), "$brand: green;\n")?;
    fs::write(override_manifest.as_path(), r#"{"sass":"./override.scss"}"#)?;

    let workspace_uri = path_to_file_uri(root.as_path());
    let source_uri = path_to_file_uri(source.as_path());
    let override_style_uri = path_to_file_uri(override_style.as_path());
    let override_manifest_path = override_manifest.to_string_lossy().to_string();
    let brand_position = parser_position_for_byte_offset(
        source_text,
        fixture_find(
            source_text,
            "$brand",
            "source fixture contains Sass variable reference",
        )? + 1,
    );
    let mut state = LspShellState::default();
    handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "workspaceFolders": [
                    {
                        "uri": workspace_uri,
                        "name": "workspace",
                    },
                ],
            },
        }),
    );
    handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "method": "workspace/didChangeConfiguration",
            "params": {
                "settings": {
                    "omena": {
                        "resolution": {
                            "packageManifestPaths": [override_manifest_path],
                        },
                    },
                },
            },
        }),
    );
    assert!(
        state
            .snapshot()
            .resolution
            .package_manifest_paths
            .iter()
            .any(|path| path.ends_with("node_modules/@design/tokens/package.lsp.json"))
    );

    for (uri, text) in [
        (source_uri.as_str(), source_text),
        (override_style_uri.as_str(), "$brand: green;\n"),
    ] {
        handle_lsp_message(
            &mut state,
            json!({
                "jsonrpc": "2.0",
                "method": "textDocument/didOpen",
                "params": {
                    "textDocument": {
                        "uri": uri,
                        "languageId": "scss",
                        "version": 1,
                        "text": text,
                    },
                },
            }),
        );
    }

    let definition = handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 2,
            "method": "textDocument/definition",
            "params": {
                "textDocument": {
                    "uri": source_uri,
                },
                "position": brand_position,
            },
        }),
    );
    assert_definition_response_single_target(&definition, override_style_uri.as_str());

    let _ = fs::remove_dir_all(root.as_path());
    Ok(())
}

#[test]
fn resolves_sass_definition_through_package_imports() -> TestResult {
    let root = std::env::temp_dir().join(format!(
        "omena_lsp_package_imports_{}_{}",
        std::process::id(),
        current_time_millis()
    ));
    let source = root.join("src/App.module.scss");
    let package_root = root.join("node_modules/@design/tokens");
    let target_style = package_root.join("dist/theme.scss");
    fs::create_dir_all(fixture_parent(source.as_path(), "source parent")?)?;
    fs::create_dir_all(fixture_parent(target_style.as_path(), "target parent")?)?;
    fs::write(
        root.join("package.json"),
        r##"{"imports":{"#theme":"@design/tokens/theme"}}"##,
    )?;
    fs::write(
        package_root.join("package.json"),
        r#"{"exports":{"./theme":{"sass":"./dist/theme.scss"}}}"#,
    )?;
    let source_text = r##"@use "#theme" as tokens;
.button { color: tokens.$brand; }
"##;
    let target_text = "$brand: green;\n";
    fs::write(source.as_path(), source_text)?;
    fs::write(target_style.as_path(), target_text)?;

    let workspace_uri = path_to_file_uri(root.as_path());
    let source_uri = path_to_file_uri(source.as_path());
    let target_style_uri = path_to_file_uri(target_style.as_path());
    let brand_position = parser_position_for_byte_offset(
        source_text,
        fixture_find(
            source_text,
            "$brand",
            "source fixture contains Sass variable reference",
        )? + 1,
    );
    let mut state = LspShellState::default();
    handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "workspaceFolders": [
                    {
                        "uri": workspace_uri,
                        "name": "workspace",
                    },
                ],
            },
        }),
    );
    for (uri, text) in [
        (source_uri.as_str(), source_text),
        (target_style_uri.as_str(), target_text),
    ] {
        handle_lsp_message(
            &mut state,
            json!({
                "jsonrpc": "2.0",
                "method": "textDocument/didOpen",
                "params": {
                    "textDocument": {
                        "uri": uri,
                        "languageId": "scss",
                        "version": 1,
                        "text": text,
                    },
                },
            }),
        );
    }

    let definition = handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 2,
            "method": "textDocument/definition",
            "params": {
                "textDocument": {
                    "uri": source_uri,
                },
                "position": brand_position,
            },
        }),
    );
    assert_definition_response_single_target(&definition, target_style_uri.as_str());

    let _ = fs::remove_dir_all(root.as_path());
    Ok(())
}

#[test]
fn indexes_foreign_package_forward_chain_for_references_without_opening_dependency() -> TestResult {
    let root = std::env::temp_dir().join(format!(
        "omena_lsp_foreign_package_reference_index_{}_{}",
        std::process::id(),
        current_time_millis()
    ));
    let source = root.join("src/App.module.scss");
    let package_root = root.join("node_modules/@acme/tokens");
    let index_style = package_root.join("_index.scss");
    let primitives_style = package_root.join("_primitives.scss");
    fs::create_dir_all(fixture_parent(source.as_path(), "source parent")?)?;
    fs::create_dir_all(package_root.as_path())?;
    fs::write(
        package_root.join("package.json"),
        r#"{"name":"@acme/tokens","version":"1.2.3","sass":"./_index.scss"}"#,
    )?;
    let source_text = r#"@use "@acme/tokens" as t;
.button { border-radius: t.$token-radius-small; }
"#;
    let index_text = r#"@forward "primitives" as token-*;"#;
    let primitives_text = "$radius-small: 4px;\n";
    fs::write(source.as_path(), source_text)?;
    fs::write(index_style.as_path(), index_text)?;
    fs::write(primitives_style.as_path(), primitives_text)?;

    let workspace_uri = path_to_file_uri(root.as_path());
    let source_uri = path_to_file_uri(source.as_path());
    let index_uri = path_to_file_uri(index_style.as_path());
    let primitives_uri = path_to_file_uri(primitives_style.as_path());
    let reference_position = parser_position_for_byte_offset(
        source_text,
        fixture_find(
            source_text,
            "$token-radius-small",
            "source fixture contains forwarded Sass variable reference",
        )? + 1,
    );
    let mut state = LspShellState::default();
    handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "workspaceFolders": [
                    {
                        "uri": workspace_uri,
                        "name": "workspace",
                    },
                ],
            },
        }),
    );
    handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "method": "textDocument/didOpen",
            "params": {
                "textDocument": {
                    "uri": source_uri,
                    "languageId": "scss",
                    "version": 1,
                    "text": source_text,
                },
            },
        }),
    );

    assert_eq!(
        state
            .document(index_uri.as_str())
            .map(|document| &document.origin),
        Some(&LspDocumentOrigin::Foreign),
        "package entrypoint should be admitted as a read-only foreign document"
    );
    assert_eq!(
        state
            .document(primitives_uri.as_str())
            .map(|document| &document.origin),
        Some(&LspDocumentOrigin::Foreign),
        "forwarded package primitive should be admitted as a read-only foreign document"
    );
    assert!(
        state.document_mut(primitives_uri.as_str()).is_none(),
        "foreign package documents must not expose mutable edit handles"
    );
    let diagnostics = lsp_style_diagnostics(&mut state, source_uri.as_str())?;
    assert!(
        diagnostics.iter().all(|diagnostic| {
            diagnostic.pointer("/code") != Some(&json!("missingSassSymbol"))
                && diagnostic.pointer("/code") != Some(&json!("missingExternalSif"))
        }),
        "forwarded foreign Sass variables should not surface missing-symbol diagnostics: {diagnostics:?}"
    );
    assert_no_foreign_path_leak("foreign Sass diagnostics", &json!(diagnostics))?;

    let definition = handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 2,
            "method": "textDocument/definition",
            "params": {
                "textDocument": {
                    "uri": source_uri,
                },
                "position": reference_position,
            },
        }),
    );
    assert_definition_response_single_target(&definition, primitives_uri.as_str());

    let references = handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 3,
            "method": "textDocument/references",
            "params": {
                "textDocument": {
                    "uri": source_uri,
                },
                "position": reference_position,
                "context": {
                    "includeDeclaration": true,
                },
            },
        }),
    );
    let locations = references
        .as_ref()
        .and_then(|response| response.pointer("/result"))
        .and_then(Value::as_array)
        .ok_or_else(|| std::io::Error::other("foreign references should return locations"))?;
    assert!(
        locations.iter().any(|location| location
            .get("uri")
            .and_then(Value::as_str)
            .is_some_and(|uri| file_uri_equivalent(uri, source_uri.as_str()))),
        "foreign declaration references should include the local consumer: {references:?}"
    );
    assert!(
        locations.iter().any(|location| location
            .get("uri")
            .and_then(Value::as_str)
            .is_some_and(|uri| file_uri_equivalent(uri, primitives_uri.as_str()))),
        "foreign declaration references should include the read-only declaration: {references:?}"
    );
    let warm_definition_json = serde_json::to_string(
        definition
            .as_ref()
            .and_then(|response| response.pointer("/result"))
            .ok_or_else(|| std::io::Error::other("warm definition should include a result"))?,
    )?;
    let warm_references_json = serde_json::to_string(
        references
            .as_ref()
            .and_then(|response| response.pointer("/result"))
            .ok_or_else(|| std::io::Error::other("warm references should include a result"))?,
    )?;
    assert_foreign_occurrence_artifacts_are_workspace_cache_confined(
        &state,
        workspace_uri.as_str(),
        package_root.as_path(),
    )?;

    state.remove_document_uri(index_uri.as_str());
    state.remove_document_uri(primitives_uri.as_str());
    *state.workspace_occurrence_index_memo_lock() = None;
    assert!(
        state.document(index_uri.as_str()).is_none()
            && state.document(primitives_uri.as_str()).is_none(),
        "evicted foreign package documents should force the cold disk-read path"
    );

    let cold_definition = handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 30,
            "method": "textDocument/definition",
            "params": {
                "textDocument": {
                    "uri": source_uri,
                },
                "position": reference_position,
            },
        }),
    );
    assert_eq!(
        warm_definition_json,
        serde_json::to_string(
            cold_definition
                .as_ref()
                .and_then(|response| response.pointer("/result"))
                .ok_or_else(|| std::io::Error::other("cold definition should include a result"))?,
        )?,
        "foreign Sass definition should be byte-identical between warm indexed and cold disk-read paths"
    );

    let cold_references = handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 31,
            "method": "textDocument/references",
            "params": {
                "textDocument": {
                    "uri": source_uri,
                },
                "position": reference_position,
                "context": {
                    "includeDeclaration": true,
                },
            },
        }),
    );
    assert_eq!(
        warm_references_json,
        serde_json::to_string(
            cold_references
                .as_ref()
                .and_then(|response| response.pointer("/result"))
                .ok_or_else(|| std::io::Error::other("cold references should include a result"))?,
        )?,
        "foreign Sass references should be byte-identical between warm indexed and cold disk-read paths"
    );

    fs::write(primitives_style.as_path(), "\n$radius-small: 4px;\n")?;
    state.remove_document_uri(index_uri.as_str());
    state.remove_document_uri(primitives_uri.as_str());
    *state.workspace_occurrence_index_memo_lock() = None;
    let shifted_definition = handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 32,
            "method": "textDocument/definition",
            "params": {
                "textDocument": {
                    "uri": source_uri,
                },
                "position": reference_position,
            },
        }),
    );
    assert_definition_response_single_target(&shifted_definition, primitives_uri.as_str());
    assert_eq!(
        shifted_definition
            .as_ref()
            .and_then(|response| response.pointer("/result/0/range/start/line"))
            .and_then(Value::as_u64),
        Some(1),
        "evicted foreign definitions should re-read changed disk content: {shifted_definition:?}"
    );

    let shifted_references = handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 33,
            "method": "textDocument/references",
            "params": {
                "textDocument": {
                    "uri": source_uri,
                },
                "position": reference_position,
                "context": {
                    "includeDeclaration": true,
                },
            },
        }),
    );
    let shifted_reference_locations = shifted_references
        .as_ref()
        .and_then(|response| response.pointer("/result"))
        .and_then(Value::as_array)
        .ok_or_else(|| {
            std::io::Error::other("shifted foreign references should return locations")
        })?;
    assert!(
        shifted_reference_locations.iter().any(|location| {
            location
                .get("uri")
                .and_then(Value::as_str)
                .is_some_and(|uri| file_uri_equivalent(uri, primitives_uri.as_str()))
                && location
                    .pointer("/range/start/line")
                    .and_then(Value::as_u64)
                    == Some(1)
        }),
        "foreign references should re-derive declaration locations from changed disk content: {shifted_references:?}"
    );

    let rename = handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 4,
            "method": "textDocument/rename",
            "params": {
                "textDocument": {
                    "uri": source_uri,
                },
                "position": reference_position,
                "newName": "$token-radius-large",
            },
        }),
    );
    let changes = rename
        .as_ref()
        .and_then(|response| response.pointer("/result/changes"))
        .and_then(Value::as_object)
        .ok_or_else(|| std::io::Error::other("rename should return local edits"))?;
    assert!(
        changes
            .keys()
            .any(|uri| file_uri_equivalent(uri.as_str(), source_uri.as_str())),
        "rename should edit the local reference: {rename:?}"
    );
    assert!(
        !changes
            .keys()
            .any(|uri| file_uri_equivalent(uri.as_str(), primitives_uri.as_str())),
        "rename must not edit foreign package declarations: {rename:?}"
    );
    assert_no_foreign_path_leak(
        "foreign Sass rename response",
        rename
            .as_ref()
            .ok_or_else(|| std::io::Error::other("rename should return a response"))?,
    )?;

    let _ = fs::remove_dir_all(root.as_path());
    Ok(())
}

#[test]
fn resolves_sass_definition_through_package_import_and_export_array_fallbacks() -> TestResult {
    let root = std::env::temp_dir().join(format!(
        "omena_lsp_package_array_fallbacks_{}_{}",
        std::process::id(),
        current_time_millis()
    ));
    let source = root.join("src/App.module.scss");
    let package_root = root.join("node_modules/@design/tokens");
    let target_style = package_root.join("dist/theme.scss");
    fs::create_dir_all(fixture_parent(source.as_path(), "source parent")?)?;
    fs::create_dir_all(fixture_parent(target_style.as_path(), "target parent")?)?;
    fs::write(
        root.join("package.json"),
        r##"{"imports":{"#theme":[{"node":"./src/theme.js"},{"style":"@design/tokens/theme"}]}}"##,
    )?;
    fs::write(
        package_root.join("package.json"),
        r#"{"exports":{"./theme":[{"import":"./dist/theme.js"},{"sass":"./dist/theme.scss"}]}}"#,
    )?;
    let source_text = r##"@use "#theme" as tokens;
.button { color: tokens.$brand; }
"##;
    let target_text = "$brand: green;\n";
    fs::write(source.as_path(), source_text)?;
    fs::write(target_style.as_path(), target_text)?;

    let workspace_uri = path_to_file_uri(root.as_path());
    let source_uri = path_to_file_uri(source.as_path());
    let target_style_uri = path_to_file_uri(target_style.as_path());
    let brand_position = parser_position_for_byte_offset(
        source_text,
        fixture_find(
            source_text,
            "$brand",
            "source fixture contains Sass variable reference",
        )? + 1,
    );
    let mut state = LspShellState::default();
    handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "workspaceFolders": [
                    {
                        "uri": workspace_uri,
                        "name": "workspace",
                    },
                ],
            },
        }),
    );
    for (uri, text) in [
        (source_uri.as_str(), source_text),
        (target_style_uri.as_str(), target_text),
    ] {
        handle_lsp_message(
            &mut state,
            json!({
                "jsonrpc": "2.0",
                "method": "textDocument/didOpen",
                "params": {
                    "textDocument": {
                        "uri": uri,
                        "languageId": "scss",
                        "version": 1,
                        "text": text,
                    },
                },
            }),
        );
    }

    let definition = handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 2,
            "method": "textDocument/definition",
            "params": {
                "textDocument": {
                    "uri": source_uri,
                },
                "position": brand_position,
            },
        }),
    );
    assert_definition_response_single_target(&definition, target_style_uri.as_str());

    let _ = fs::remove_dir_all(root.as_path());
    Ok(())
}

#[test]
fn workspace_lock_external_sifs_are_not_automatic_lsp_inputs() -> TestResult {
    let root = std::env::temp_dir().join(format!(
        "omena_lsp_lock_external_sifs_{}_{}",
        std::process::id(),
        current_time_millis()
    ));
    let source = root.join("src/App.module.scss");
    let sif_path = root.join("sif/tokens.sif.json");
    fs::create_dir_all(fixture_parent(source.as_path(), "source parent")?)?;
    fs::create_dir_all(fixture_parent(sif_path.as_path(), "sif parent")?)?;

    let source_text = r#"@use "https://cdn.example/tokens.scss" as tokens;
.button { color: tokens.$brand; }"#;
    fs::write(source.as_path(), source_text)?;

    let sif = fixture_external_sif("https://cdn.example/tokens.scss")?;
    fs::write(
        sif_path.as_path(),
        omena_sif::write_omena_sif_json_v1(&sif)?,
    )?;
    let lock = omena_sif::OmenaLockV1::new(vec![omena_sif::build_omena_lock_sif_entry_v1(
        "sif/tokens.sif.json",
        &sif,
    )?]);
    fs::write(
        root.join("omena.lock"),
        omena_sif::write_omena_lock_json_v1(&lock)?,
    )?;

    let workspace_uri = path_to_file_uri(root.as_path());
    let source_uri = path_to_file_uri(source.as_path());
    let mut state = LspShellState::default();
    handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "workspaceFolders": [
                    {
                        "uri": workspace_uri,
                        "name": "workspace",
                    },
                ],
            },
        }),
    );
    assert!(
        state.resolution.external_sifs.is_empty(),
        "a digest-consistent lock-only SIF must not become an automatic input"
    );

    open_style_document(&mut state, source_uri.as_str(), source_text);
    let diagnostics = lsp_style_diagnostics(&mut state, source_uri.as_str())?;
    assert!(
        diagnostics.iter().any(|diagnostic| {
            diagnostic.pointer("/code") == Some(&json!("missingSassSymbol"))
                || diagnostic.pointer("/code") == Some(&json!("missingExternalSif"))
        }),
        "unregenerable lock bytes must not suppress the blocking diagnostic: {diagnostics:?}"
    );

    let _ = fs::remove_dir_all(root.as_path());
    Ok(())
}

#[test]
fn auto_discovered_lsp_lock_bytes_are_never_read_or_admitted() -> TestResult {
    let root = std::env::temp_dir().join(format!(
        "omena_lsp_lock_digest_refusal_{}_{}",
        std::process::id(),
        current_time_millis()
    ));
    let sif_path = root.join("sif/tokens.sif.json");
    fs::create_dir_all(fixture_parent(sif_path.as_path(), "sif parent")?)?;

    let canonical_url = "https://cdn.example/tokens.scss";
    let expected_sif = fixture_external_sif(canonical_url)?;
    let mut poisoned_sif = expected_sif.clone();
    poisoned_sif.exports.variables[0].value_repr = Some("poisoned".to_string());
    fs::write(
        sif_path.as_path(),
        omena_sif::write_omena_sif_json_v1(&poisoned_sif)?,
    )?;
    let lock = omena_sif::OmenaLockV1::new(vec![omena_sif::build_omena_lock_sif_entry_v1(
        "sif/tokens.sif.json",
        &poisoned_sif,
    )?]);
    fs::write(
        root.join("omena.lock"),
        omena_sif::write_omena_lock_json_v1(&lock)?,
    )?;

    let workspace_uri = path_to_file_uri(root.as_path());
    let mut state = LspShellState::default();
    handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "workspaceFolders": [{ "uri": workspace_uri, "name": "workspace" }],
            },
        }),
    );

    enable_deferred_external_sif_refresh(&mut state);
    let job = prepare_deferred_external_sif_refresh_job(&mut state)
        .ok_or_else(|| "lock-bearing deferred SIF job was not prepared".to_string())?;
    assert_eq!(
        job.lockfiles.len(),
        1,
        "the product collector arm must receive the discovered workspace lock"
    );
    let result = collect_deferred_external_sif_refresh(job);
    assert_eq!(
        result.lock_read_count, 0,
        "the retired lock-read compatibility field must stay zero"
    );
    assert!(
        result
            .external_sifs
            .iter()
            .all(|input| input.canonical_url != canonical_url),
        "a lock-bearing deferred job must not admit the lock SIF"
    );
    assert!(!apply_deferred_external_sif_refresh_result(
        &mut state, result
    ));

    assert!(
        state
            .resolution
            .external_sifs
            .iter()
            .all(|input| input.canonical_url != canonical_url),
        "an auto-discovered lock SIF must not enter the LSP product state, regardless of its self-consistency"
    );

    let _ = fs::remove_dir_all(root.as_path());
    Ok(())
}

#[test]
fn lsp_local_bridge_is_the_sole_automatic_external_sif_authority() -> TestResult {
    let root = std::env::temp_dir().join(format!(
        "omena_lsp_lock_bridge_precedence_{}_{}",
        std::process::id(),
        current_time_millis()
    ));
    let source = root.join("src/App.module.scss");
    let external = root.join("vendor/_tokens.scss");
    let sif_path = root.join("sif/tokens.sif.json");
    fs::create_dir_all(fixture_parent(source.as_path(), "source parent")?)?;
    fs::create_dir_all(fixture_parent(external.as_path(), "external parent")?)?;
    fs::create_dir_all(fixture_parent(sif_path.as_path(), "sif parent")?)?;

    let external_source = "$brand: red !default;\n";
    fs::write(external.as_path(), external_source)?;
    let external_uri = path_to_file_uri(external.as_path());
    let expected_sif =
        omena_sif::generate_static_omena_sif_v1(omena_sif::OmenaSifStaticGeneratorInputV1 {
            canonical_url: external_uri.as_str(),
            source: external_source,
            syntax: omena_sif::OmenaSifSourceSyntaxV1::Scss,
        })?;
    let mut poisoned_sif = expected_sif.clone();
    poisoned_sif.exports.variables[0].value_repr = Some("poisoned".to_string());
    fs::write(
        sif_path.as_path(),
        omena_sif::write_omena_sif_json_v1(&poisoned_sif)?,
    )?;
    let lock = omena_sif::OmenaLockV1::new(vec![omena_sif::build_omena_lock_sif_entry_v1(
        "sif/tokens.sif.json",
        &poisoned_sif,
    )?]);
    fs::write(
        root.join("omena.lock"),
        omena_sif::write_omena_lock_json_v1(&lock)?,
    )?;

    let source_text = format!(
        "@use \"{}\" as tokens;\n.button {{ color: tokens.$brand; }}\n",
        external_uri
    );
    fs::write(source.as_path(), source_text.as_str())?;
    let workspace_uri = path_to_file_uri(root.as_path());
    let source_uri = path_to_file_uri(source.as_path());
    let mut state = LspShellState::default();
    handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "workspaceFolders": [{ "uri": workspace_uri, "name": "workspace" }],
            },
        }),
    );
    open_style_document(&mut state, source_uri.as_str(), source_text.as_str());

    let admitted = state
        .resolution
        .external_sifs
        .iter()
        .find(|input| input.canonical_url == external_uri)
        .ok_or_else(|| std::io::Error::other("locally regenerated bridge SIF"))?;
    assert_eq!(
        admitted.sif, expected_sif,
        "the automatic LSP path must admit only the locally regenerated bridge SIF"
    );
    assert_ne!(admitted.sif, poisoned_sif);

    let _ = fs::remove_dir_all(root.as_path());
    Ok(())
}

#[test]
fn source_absent_lock_sif_exports_do_not_enter_lsp_language_features() -> TestResult {
    let root = std::env::temp_dir().join(format!(
        "omena_lsp_source_absent_sif_exports_{}_{}",
        std::process::id(),
        current_time_millis()
    ));
    let source = root.join("src/App.module.scss");
    let sif_path = root.join("sif/tokens.sif.json");
    fs::create_dir_all(fixture_parent(source.as_path(), "source parent")?)?;
    fs::create_dir_all(fixture_parent(sif_path.as_path(), "sif parent")?)?;

    let source_text = r#"@use "https://cdn.example/tokens.scss" as tokens;
.button {
  color: tokens.$brand;
  border-color: tokens.$brand;
  outline-color: tokens.;
}"#;
    fs::write(source.as_path(), source_text)?;
    let sif = fixture_external_sif("https://cdn.example/tokens.scss")?;
    fs::write(
        sif_path.as_path(),
        omena_sif::write_omena_sif_json_v1(&sif)?,
    )?;
    let lock = omena_sif::OmenaLockV1::new(vec![omena_sif::build_omena_lock_sif_entry_v1(
        "sif/tokens.sif.json",
        &sif,
    )?]);
    fs::write(
        root.join("omena.lock"),
        omena_sif::write_omena_lock_json_v1(&lock)?,
    )?;

    let workspace_uri = path_to_file_uri(root.as_path());
    let source_uri = path_to_file_uri(source.as_path());
    let reference_position = parser_position_for_byte_offset(
        source_text,
        fixture_find(
            source_text,
            "$brand",
            "source fixture contains SIF-backed Sass variable reference",
        )? + 1,
    );
    let mut state = LspShellState::default();
    handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "workspaceFolders": [
                    {
                        "uri": workspace_uri,
                        "name": "workspace",
                    },
                ],
            },
        }),
    );
    open_style_document(&mut state, source_uri.as_str(), source_text);

    let hover = handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 2,
            "method": "textDocument/hover",
            "params": {
                "textDocument": {
                    "uri": source_uri,
                },
                "position": reference_position,
            },
        }),
    );
    let hover_text = hover
        .as_ref()
        .and_then(|response| response.pointer("/result/contents/value"))
        .and_then(Value::as_str)
        .ok_or_else(|| std::io::Error::other("ordinary source hover should render markdown"))?;
    assert!(
        !hover_text.contains("External Sass interface"),
        "{hover_text}"
    );
    assert!(!hover_text.contains("Value: `red`"), "{hover_text}");

    let definition = handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 3,
            "method": "textDocument/definition",
            "params": {
                "textDocument": {
                    "uri": source_uri,
                },
                "position": reference_position,
            },
        }),
    );
    assert!(
        definition
            .as_ref()
            .and_then(|response| response.pointer("/result"))
            .is_some_and(Value::is_null),
        "unregenerable lock-only symbols must not fabricate definition locations: {definition:?}"
    );

    let references = handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 4,
            "method": "textDocument/references",
            "params": {
                "textDocument": {
                    "uri": source_uri,
                },
                "position": reference_position,
                "context": {
                    "includeDeclaration": true,
                },
            },
        }),
    );
    let reference_locations = references
        .as_ref()
        .and_then(|response| response.pointer("/result"))
        .and_then(Value::as_array)
        .ok_or_else(|| std::io::Error::other("local references should return locations"))?;
    assert_eq!(
        reference_locations.len(),
        2,
        "references may join the two local uses, but must not add a lock-only declaration: {references:?}"
    );
    assert!(
        reference_locations.iter().all(|location| location
            .get("uri")
            .and_then(Value::as_str)
            .is_some_and(|uri| file_uri_equivalent(uri, source_uri.as_str()))),
        "references should stay on source locations only: {references:?}"
    );
    let diagnostics = lsp_style_diagnostics(&mut state, source_uri.as_str())?;
    assert!(
        diagnostics.iter().any(|diagnostic| {
            diagnostic.pointer("/code") == Some(&json!("missingSassSymbol"))
                || diagnostic.pointer("/code") == Some(&json!("missingExternalSif"))
        }),
        "source-absent lock bytes must not suppress the blocking diagnostic: {diagnostics:?}"
    );

    let _ = fs::remove_dir_all(root.as_path());
    Ok(())
}

#[test]
fn watched_lock_only_external_sifs_remain_unserved_without_local_regeneration() -> TestResult {
    let root = std::env::temp_dir().join(format!(
        "omena_lsp_lock_watch_external_sifs_{}_{}",
        std::process::id(),
        current_time_millis()
    ));
    let source = root.join("src/App.module.scss");
    let sif_path = root.join("sif/tokens.sif.json");
    let lock_path = root.join("omena.lock");
    fs::create_dir_all(fixture_parent(source.as_path(), "source parent")?)?;
    fs::create_dir_all(fixture_parent(sif_path.as_path(), "sif parent")?)?;

    let source_text = r#"@use "https://cdn.example/tokens.scss" as tokens;
.button { color: tokens.$brand; }"#;
    fs::write(source.as_path(), source_text)?;

    let workspace_uri = path_to_file_uri(root.as_path());
    let source_uri = path_to_file_uri(source.as_path());
    let lock_uri = path_to_file_uri(lock_path.as_path());
    let mut state = LspShellState::default();
    handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "workspaceFolders": [
                    {
                        "uri": workspace_uri,
                        "name": "workspace",
                    },
                ],
            },
        }),
    );
    open_style_document(&mut state, source_uri.as_str(), source_text);
    assert!(
        state.resolution.external_sifs.is_empty(),
        "workspace starts without lock-backed external SIFs"
    );

    let sif = fixture_external_sif("https://cdn.example/tokens.scss")?;
    fs::write(
        sif_path.as_path(),
        omena_sif::write_omena_sif_json_v1(&sif)?,
    )?;
    let lock = omena_sif::OmenaLockV1::new(vec![omena_sif::build_omena_lock_sif_entry_v1(
        "sif/tokens.sif.json",
        &sif,
    )?]);
    fs::write(
        lock_path.as_path(),
        omena_sif::write_omena_lock_json_v1(&lock)?,
    )?;
    handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "method": "workspace/didChangeWatchedFiles",
            "params": {
                "changes": [
                    {
                        "uri": lock_uri,
                        "type": 2,
                    },
                ],
            },
        }),
    );

    assert!(
        state.resolution.external_sifs.is_empty(),
        "watching a new lock entry must not turn lock-only bytes into automatic LSP authority"
    );
    let diagnostics = lsp_style_diagnostics(&mut state, source_uri.as_str())?;
    assert!(
        diagnostics.iter().any(|diagnostic| {
            diagnostic.pointer("/code") == Some(&json!("missingSassSymbol"))
                || diagnostic.pointer("/code") == Some(&json!("missingExternalSif"))
        }),
        "watched lock-only bytes must not suppress the blocking diagnostic: {diagnostics:?}"
    );

    let _ = fs::remove_dir_all(root.as_path());
    Ok(())
}

#[test]
fn bridges_file_external_sass_edges_for_lsp_style_diagnostics() -> TestResult {
    let root = std::env::temp_dir().join(format!(
        "omena_lsp_bridge_external_sifs_{}_{}",
        std::process::id(),
        current_time_millis()
    ));
    let source = root.join("src/App.module.scss");
    let external = root.join("vendor/_tokens.scss");
    fs::create_dir_all(fixture_parent(source.as_path(), "source parent")?)?;
    fs::create_dir_all(fixture_parent(external.as_path(), "external parent")?)?;
    fs::write(external.as_path(), "$brand: red !default;\n")?;

    let external_uri = path_to_file_uri(external.as_path());
    let source_text = format!(
        "@use \"{}\" as tokens;\n.button {{ color: tokens.$brand; }}",
        external_uri
    );
    fs::write(source.as_path(), source_text.as_str())?;

    let workspace_uri = path_to_file_uri(root.as_path());
    let source_uri = path_to_file_uri(source.as_path());
    let mut state = LspShellState::default();
    handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "workspaceFolders": [
                    {
                        "uri": workspace_uri,
                        "name": "workspace",
                    },
                ],
            },
        }),
    );
    open_style_document(&mut state, source_uri.as_str(), source_text.as_str());

    assert!(
        state
            .resolution
            .external_sifs
            .iter()
            .any(|sif| sif.canonical_url == external_uri),
        "opening a style document should bridge readable file:// external Sass edges"
    );
    let diagnostics = lsp_style_diagnostics(&mut state, source_uri.as_str())?;
    assert!(
        diagnostics.iter().all(|diagnostic| {
            diagnostic.pointer("/code") != Some(&json!("missingSassSymbol"))
                && diagnostic.pointer("/code") != Some(&json!("missingExternalSif"))
        }),
        "bridge-generated external SIF should satisfy the file:// Sass reference: {diagnostics:?}"
    );

    let _ = fs::remove_dir_all(root.as_path());
    Ok(())
}

#[test]
fn lsp_bridge_refuses_unverified_recorded_shard_verdict() -> TestResult {
    let root = std::env::temp_dir().join(format!(
        "omena_lsp_recorded_shard_verdict_{}_{}",
        std::process::id(),
        current_time_millis()
    ));
    let source = root.join("src/App.module.scss");
    let external = root.join("vendor/_tokens.scss");
    fs::create_dir_all(fixture_parent(source.as_path(), "source parent")?)?;
    fs::create_dir_all(fixture_parent(external.as_path(), "external parent")?)?;
    let external_source = "$brand: red !default;\n";
    fs::write(external.as_path(), external_source)?;

    let external_uri = path_to_file_uri(external.as_path());
    let sif = omena_sif::generate_static_omena_sif_v1(omena_sif::OmenaSifStaticGeneratorInputV1 {
        canonical_url: external_uri.as_str(),
        source: external_source,
        syntax: omena_sif::OmenaSifSourceSyntaxV1::Scss,
    })?;
    let sif_hash = omena_sif::compute_omena_sif_artifact_hash_v1(&sif)?;
    let verdict = omena_sif::OmenaSifShardRecordedVerdictV1 {
        schema_version: omena_sif::OMENA_SIF_SHARD_RECORDED_VERDICT_SCHEMA_VERSION_V1.to_string(),
        product: omena_sif::OMENA_SIF_SHARD_RECORDED_VERDICT_PRODUCT_V1.to_string(),
        verification_owner: omena_sif::OMENA_SIF_SHARD_VERIFICATION_OWNER_V1.to_string(),
        canonical_url: external_uri.clone(),
        sif_hash: sif_hash.clone(),
        trust_tier: omena_sif::OmenaSifTrustTierV1::T2,
        signature: omena_sif::OmenaSifShardSignatureV1 {
            algorithm_version: omena_sif::OMENA_SIF_SHARD_SIGNATURE_ALGORITHM_VERSION_V1
                .to_string(),
            reference: "fixture:keyless-attestation".to_string(),
            signed_payload_digest: sif_hash.clone(),
        },
    };
    let verdict_dir = root
        .join(".cache/omena")
        .join(omena_sif::OMENA_SIF_SHARD_VERDICT_DIR_V1);
    fs::create_dir_all(verdict_dir.as_path())?;
    let address = omena_sif::compute_omena_sif_shard_recorded_verdict_address_v1(
        external_uri.as_str(),
        &sif_hash,
    )?;
    let verdict_file = address
        .as_str()
        .strip_prefix("blake3:")
        .ok_or_else(|| std::io::Error::other("verdict address"))?;
    fs::write(
        verdict_dir.join(format!("{verdict_file}.json")),
        omena_sif::write_omena_sif_shard_recorded_verdict_json_v1(&verdict)?,
    )?;

    let source_text = format!(
        "@use \"{}\" as tokens;\n.button {{ color: tokens.$brand; }}",
        external_uri
    );
    fs::write(source.as_path(), source_text.as_str())?;
    let workspace_uri = path_to_file_uri(root.as_path());
    let source_uri = path_to_file_uri(source.as_path());
    let mut state = LspShellState::default();
    handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "workspaceFolders": [{ "uri": workspace_uri, "name": "workspace" }],
            },
        }),
    );
    open_style_document(&mut state, source_uri.as_str(), source_text.as_str());

    let trust = state
        .resolution
        .external_sif_trust_records
        .get(external_uri.as_str())
        .ok_or_else(|| std::io::Error::other("recorded external SIF trust"))?;
    assert_eq!(trust.trust_tier, omena_sif::OmenaSifTrustTierV1::T1);
    assert_eq!(
        trust.trust_source,
        omena_query::OmenaQueryExternalSifTrustSourceV1::UnsignedLegacy
    );

    let _ = fs::remove_dir_all(root.as_path());
    Ok(())
}

#[test]
fn trust_record_projection_rechecks_the_omena_published_subject() -> TestResult {
    const BUNDLE_SHA256: &str = "0c99e37ac1b1d3cbfd677416a74218c9a1ca8e28c3aac95c7614549f3b3b0ce1";
    const PUBLISHED_URL: &str = "pkg:omena-fixture/external-sif-trust.css";
    let root = std::env::temp_dir().join(format!(
        "omena_lsp_published_sif_subject_{}_{}",
        std::process::id(),
        current_time_millis()
    ));
    fs::create_dir_all(root.as_path())?;
    let style = root.join("CssOnly.module.css");
    let source =
        include_str!("../../../../../examples/src/scenarios/08-css-only/CssOnly.module.css");
    fs::write(style.as_path(), source)?;
    let resolved_url = path_to_file_uri(style.as_path());
    let published_sif = omena_sif::read_omena_sif_json_v1(
        include_str!("../../../omena-bridge/tests/fixtures/published-sif-attestation.sif.json")
            .trim_end(),
    )?;
    let cache_root = root.join(".cache/omena");
    let storage =
        omena_query::OmenaQueryExternalSifStorageV0::from_workspace_cache_root(cache_root);
    let verdict_dir = storage
        .recorded_verdict_dir()
        .ok_or_else(|| std::io::Error::other("recorded verdict directory"))?;
    let bundle_reference = format!("bundles-v1/{BUNDLE_SHA256}.sigstore.json");
    let bundle_path = verdict_dir.join(bundle_reference.as_str());
    fs::create_dir_all(fixture_parent(bundle_path.as_path(), "bundle parent")?)?;
    fs::write(
        bundle_path.as_path(),
        include_bytes!(
            "../../../omena-bridge/tests/fixtures/published-sif-attestation.sigstore.json"
        ),
    )?;
    let sif_hash = omena_sif::compute_omena_sif_artifact_hash_v1(&published_sif)?;
    let verdict = omena_sif::OmenaSifShardRecordedVerdictV1 {
        schema_version: omena_sif::OMENA_SIF_SHARD_RECORDED_VERDICT_SCHEMA_VERSION_V1.to_string(),
        product: omena_sif::OMENA_SIF_SHARD_RECORDED_VERDICT_PRODUCT_V1.to_string(),
        verification_owner: omena_sif::OMENA_SIF_SHARD_VERIFICATION_OWNER_V1.to_string(),
        canonical_url: PUBLISHED_URL.to_string(),
        sif_hash: sif_hash.clone(),
        trust_tier: omena_sif::OmenaSifTrustTierV1::T3,
        signature: omena_sif::OmenaSifShardSignatureV1 {
            algorithm_version: omena_sif::OMENA_SIF_SHARD_SIGNATURE_ALGORITHM_VERSION_V1
                .to_string(),
            reference: bundle_reference,
            signed_payload_digest: sif_hash.clone(),
        },
    };
    let verdict_address =
        omena_sif::compute_omena_sif_shard_recorded_verdict_address_v1(PUBLISHED_URL, &sif_hash)?;
    let verdict_name = verdict_address
        .as_str()
        .strip_prefix("blake3:")
        .ok_or_else(|| std::io::Error::other("recorded verdict address"))?;
    fs::write(
        verdict_dir.join(format!("{verdict_name}.json")),
        omena_sif::write_omena_sif_shard_recorded_verdict_json_v1(&verdict)?,
    )?;

    let resolve = || {
        omena_query::resolve_omena_query_bridge_external_sifs_for_seed_pairs_with_cache_storage_and_trust(
            std::iter::once((PUBLISHED_URL.to_string(), resolved_url.clone())),
            &[],
            &omena_query::OmenaQueryStyleResolutionInputsV0::default(),
            &storage,
        )
    };
    let mut state = LspShellState::default();
    let elevated = resolve();
    state.resolution.external_sifs = elevated.resolution.external_sifs;
    state.resolution.external_sif_trust_records =
        crate::external_sif_loader::external_sif_trust_record_map(elevated.trust_records);
    let elevated_trust = state
        .resolution
        .external_sif_trust_records
        .get(PUBLISHED_URL)
        .ok_or_else(|| std::io::Error::other("published external SIF trust"))?;
    assert_eq!(
        elevated_trust.trust_tier,
        omena_sif::OmenaSifTrustTierV1::T3
    );
    assert_eq!(
        elevated_trust.trust_source,
        omena_query::OmenaQueryExternalSifTrustSourceV1::RecordedVerdict
    );

    let poisoned_source = format!("{source}\n/* substituted after publication */\n");
    fs::write(style.as_path(), poisoned_source.as_str())?;
    let poisoned_sif =
        omena_sif::generate_static_omena_sif_v1(omena_sif::OmenaSifStaticGeneratorInputV1 {
            canonical_url: PUBLISHED_URL,
            source: poisoned_source.as_str(),
            syntax: omena_sif::OmenaSifSourceSyntaxV1::Css,
        })?;
    let poisoned_hash = omena_sif::compute_omena_sif_artifact_hash_v1(&poisoned_sif)?;
    let poisoned_verdict = omena_sif::OmenaSifShardRecordedVerdictV1 {
        canonical_url: PUBLISHED_URL.to_string(),
        sif_hash: poisoned_hash.clone(),
        signature: omena_sif::OmenaSifShardSignatureV1 {
            algorithm_version: omena_sif::OMENA_SIF_SHARD_SIGNATURE_ALGORITHM_VERSION_V1
                .to_string(),
            reference: verdict.signature.reference.clone(),
            signed_payload_digest: poisoned_hash.clone(),
        },
        ..verdict.clone()
    };
    let poisoned_verdict_address = omena_sif::compute_omena_sif_shard_recorded_verdict_address_v1(
        PUBLISHED_URL,
        &poisoned_hash,
    )?;
    let poisoned_verdict_name = poisoned_verdict_address
        .as_str()
        .strip_prefix("blake3:")
        .ok_or_else(|| std::io::Error::other("poisoned recorded verdict address"))?;
    fs::write(
        verdict_dir.join(format!("{poisoned_verdict_name}.json")),
        omena_sif::write_omena_sif_shard_recorded_verdict_json_v1(&poisoned_verdict)?,
    )?;
    let substituted = resolve();
    state.resolution.external_sifs = substituted.resolution.external_sifs;
    state.resolution.external_sif_trust_records =
        crate::external_sif_loader::external_sif_trust_record_map(substituted.trust_records);
    let substituted_trust = state
        .resolution
        .external_sif_trust_records
        .get(PUBLISHED_URL)
        .ok_or_else(|| std::io::Error::other("substituted external SIF trust"))?;
    assert_eq!(
        substituted_trust.trust_tier,
        omena_sif::OmenaSifTrustTierV1::T1
    );
    assert_eq!(
        substituted_trust.trust_source,
        omena_query::OmenaQueryExternalSifTrustSourceV1::UnsignedLegacy
    );

    fs::write(style.as_path(), source)?;
    fs::write(bundle_path, b"{}")?;
    let downgraded = resolve();
    state.resolution.external_sifs = downgraded.resolution.external_sifs;
    state.resolution.external_sif_trust_records =
        crate::external_sif_loader::external_sif_trust_record_map(downgraded.trust_records);
    let downgraded_trust = state
        .resolution
        .external_sif_trust_records
        .get(PUBLISHED_URL)
        .ok_or_else(|| std::io::Error::other("downgraded external SIF trust"))?;
    assert_eq!(
        downgraded_trust.trust_tier,
        omena_sif::OmenaSifTrustTierV1::T1
    );
    assert_eq!(
        downgraded_trust.trust_source,
        omena_query::OmenaQueryExternalSifTrustSourceV1::UnsignedLegacy
    );

    let _ = fs::remove_dir_all(root.as_path());
    Ok(())
}

#[test]
fn bridges_bare_package_forward_chain_for_lsp_style_diagnostics() -> TestResult {
    let root = std::env::temp_dir().join(format!(
        "omena_lsp_bare_package_forward_sifs_{}_{}",
        std::process::id(),
        current_time_millis()
    ));
    let source = root.join("src/App.module.scss");
    let app_package = root.join("node_modules/@app/theme");
    let design_package = root.join("node_modules/@design/tokens");
    fs::create_dir_all(fixture_parent(source.as_path(), "source parent")?)?;
    fs::create_dir_all(app_package.as_path())?;
    fs::create_dir_all(design_package.as_path())?;
    fs::write(
        app_package.join("package.json"),
        r#"{"exports":{"./index":{"sass":"./index.scss"}}}"#,
    )?;
    fs::write(
        design_package.join("package.json"),
        r#"{"exports":{"./colors":{"sass":"./colors.scss"}}}"#,
    )?;
    fs::write(
        app_package.join("index.scss"),
        "@forward \"@design/tokens/colors\";\n@forward \"./radius\";\n",
    )?;
    fs::write(app_package.join("_radius.scss"), "$ds_radius-card: 12px;\n")?;
    fs::write(design_package.join("colors.scss"), "$ds_gray-700: #333;\n")?;

    let source_text = "@use \"@app/theme/index\" as ds;\n.button { color: ds.$ds_gray-700; border-radius: ds.$ds_radius-card; }\n";
    fs::write(source.as_path(), source_text)?;

    let workspace_uri = path_to_file_uri(root.as_path());
    let source_uri = path_to_file_uri(source.as_path());
    let mut state = LspShellState::default();
    handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "workspaceFolders": [
                    {
                        "uri": workspace_uri,
                        "name": "workspace",
                    },
                ],
            },
        }),
    );
    open_style_document(&mut state, source_uri.as_str(), source_text);

    assert!(
        state
            .resolution
            .external_sifs
            .iter()
            .any(|sif| sif.canonical_url == "@design/tokens/colors"),
        "bare transitive forward should be represented as a verbatim external SIF alias: {:?}",
        state.resolution.external_sifs
    );
    let diagnostics = lsp_style_diagnostics(&mut state, source_uri.as_str())?;
    assert!(
        diagnostics.iter().all(|diagnostic| {
            diagnostic.pointer("/code") != Some(&json!("missingSassSymbol"))
                && diagnostic.pointer("/code") != Some(&json!("missingExternalSif"))
        }),
        "bare package forward chain should satisfy Sass references: {diagnostics:?}"
    );

    let _ = fs::remove_dir_all(root.as_path());
    Ok(())
}

#[test]
fn style_document_bridge_changes_refresh_external_sifs_without_corpus_rebuild() -> TestResult {
    let root = std::env::temp_dir().join(format!(
        "omena_lsp_bridge_external_sifs_delta_{}_{}",
        std::process::id(),
        current_time_millis()
    ));
    let source = root.join("src/App.module.scss");
    let peer = root.join("src/Peer.module.scss");
    let external_a = root.join("vendor/_a.scss");
    let external_b = root.join("vendor/_b.scss");
    fs::create_dir_all(fixture_parent(source.as_path(), "source parent")?)?;
    fs::create_dir_all(fixture_parent(peer.as_path(), "peer parent")?)?;
    fs::create_dir_all(fixture_parent(external_a.as_path(), "external parent")?)?;
    fs::write(
        root.join("omena.lock"),
        r#"{"lockfileVersion":"1","entries":[]}"#,
    )?;
    fs::write(source.as_path(), ".button { color: red; }\n")?;
    fs::write(external_a.as_path(), "$brand-a: red !default;\n")?;
    fs::write(external_b.as_path(), "$brand-b: blue !default;\n")?;

    let workspace_uri = path_to_file_uri(root.as_path());
    let source_uri = path_to_file_uri(source.as_path());
    let peer_uri = path_to_file_uri(peer.as_path());
    let external_a_uri = path_to_file_uri(external_a.as_path());
    let external_b_uri = path_to_file_uri(external_b.as_path());
    let peer_text = format!(
        "@use \"{}\" as tokens;\n.peer {{ color: tokens.$brand-a; }}\n",
        external_a_uri
    );
    let source_initial_text = ".button { color: red; }\n";
    let source_changed_text = format!(
        "@use \"{}\" as tokens;\n.button {{ color: tokens.$brand-b; }}\n",
        external_b_uri
    );

    let mut state = LspShellState::default();
    handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "workspaceFolders": [
                    {
                        "uri": workspace_uri,
                        "name": "workspace",
                    },
                ],
            },
        }),
    );
    open_style_document(&mut state, peer_uri.as_str(), peer_text.as_str());
    open_style_document(&mut state, source_uri.as_str(), source_initial_text);

    let bridge_generations_before_change = state.external_sif_bridge_generation_count;
    handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "method": "textDocument/didChange",
            "params": {
                "textDocument": {
                    "uri": source_uri,
                    "version": 2,
                },
                "contentChanges": [
                    {
                        "text": source_changed_text,
                    },
                ],
            },
        }),
    );

    assert_eq!(
        state.external_sif_bridge_generation_count - bridge_generations_before_change,
        1,
        "bridge source didChange should generate only the newly-added bridge SIF"
    );
    assert!(
        state
            .resolution
            .external_sifs
            .iter()
            .any(|sif| sif.canonical_url == external_a_uri),
        "existing bridge SIF from another document must remain active"
    );
    assert!(
        state
            .resolution
            .external_sifs
            .iter()
            .any(|sif| sif.canonical_url == external_b_uri),
        "new bridge SIF from the changed document must be added"
    );

    let _ = fs::remove_dir_all(root.as_path());
    Ok(())
}

fn fixture_external_sif(canonical_url: &str) -> Result<omena_sif::OmenaSifV1, serde_json::Error> {
    omena_sif::OmenaSifV1::from_static_exports(
        canonical_url,
        omena_sif::OmenaSifGeneratorV1 {
            name: "fixture-sifgen".to_string(),
            version: "0.1.0".to_string(),
            toolchain_id: "fixture-sifgen@0.1.0".to_string(),
        },
        omena_sif::OmenaSifSourceV1 {
            syntax: omena_sif::OmenaSifSourceSyntaxV1::Scss,
        },
        omena_sif::OmenaSifExportsV1 {
            variables: vec![omena_sif::OmenaSifVariableExportV1 {
                name: "$brand".to_string(),
                defaulted: true,
                value_repr: Some("red".to_string()),
            }],
            mixins: Vec::new(),
            functions: Vec::new(),
            placeholders: Vec::new(),
            forwards: Vec::new(),
        },
        Vec::new(),
        b"$brand: red !default;",
    )
}

fn open_style_document(state: &mut LspShellState, uri: &str, text: &str) {
    handle_lsp_message(
        state,
        json!({
            "jsonrpc": "2.0",
            "method": "textDocument/didOpen",
            "params": {
                "textDocument": {
                    "uri": uri,
                    "languageId": "scss",
                    "version": 1,
                    "text": text,
                },
            },
        }),
    );
}

fn lsp_style_diagnostics(
    state: &mut LspShellState,
    uri: &str,
) -> Result<Vec<Value>, Box<dyn std::error::Error>> {
    let response = handle_lsp_message(
        state,
        json!({
            "jsonrpc": "2.0",
            "id": 2,
            "method": STYLE_DIAGNOSTICS_REQUEST,
            "params": {
                "textDocument": {
                    "uri": uri,
                },
            },
        }),
    );
    response
        .as_ref()
        .and_then(|value| value.pointer("/result"))
        .and_then(Value::as_array)
        .cloned()
        .ok_or_else(|| std::io::Error::other("style diagnostics response contains an array").into())
}

fn assert_no_foreign_path_leak(label: &str, value: &Value) -> TestResult {
    let serialized = serde_json::to_string(value)?;
    assert!(
        !serialized.contains("node_modules"),
        "{label} must not expose node_modules-origin paths: {serialized}"
    );
    Ok(())
}

fn assert_foreign_occurrence_artifacts_are_workspace_cache_confined(
    _state: &LspShellState,
    workspace_uri: &str,
    package_root: &Path,
) -> TestResult {
    let workspace_root = file_uri_to_path(workspace_uri)
        .ok_or_else(|| std::io::Error::other("workspace URI should map to a file path"))?;
    let workspace_cache_root = workspace_root.join(".cache").join("omena");
    assert!(
        workspace_cache_root
            .join("workspace-occurrence-shards-v2")
            .exists(),
        "foreign occurrence shards should be persisted below the workspace cache root"
    );
    assert!(
        !package_root.join(".cache").join("omena").exists(),
        "foreign package directories must not receive omena cache artifacts"
    );
    Ok(())
}