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
use super::*;
use omena_query::{
    OmenaQuerySourceDocumentInputV0, OmenaQueryStylePackageManifestV0, OmenaQueryStyleSourceInputV0,
};
use std::path::PathBuf;

const DISK_CACHE_STYLE_TEXT: &str =
    ":root { --brand: red; }\n.btn { width: var(--missing); color: red; color: blue; }";

fn disk_cache_workspace_root(suffix: &str) -> PathBuf {
    let workspace_root = std::env::temp_dir().join(format!(
        "omena-lsp-server-disk-cache-{suffix}-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&workspace_root);
    workspace_root
}

fn write_disk_cache_style_fixture(workspace_root: &Path, text: &str) -> (String, String) {
    let src_dir = workspace_root.join("src");
    let style_path = src_dir.join("App.module.scss");
    let create_dir_result = std::fs::create_dir_all(&src_dir);
    assert!(
        create_dir_result.is_ok(),
        "create disk-cache fixture directory: {:?}",
        create_dir_result.err(),
    );
    let write_result = std::fs::write(&style_path, text);
    assert!(
        write_result.is_ok(),
        "write disk-cache style fixture: {:?}",
        write_result.err(),
    );
    (
        format!("file://{}", workspace_root.display()),
        format!("file://{}", style_path.display()),
    )
}

fn run_disk_cache_session(
    workspace_uri: &str,
    style_uri: &str,
    style_text: &str,
) -> Vec<ScheduledLspOutput> {
    run_disk_cache_session_with_state(
        LspShellState::default(),
        workspace_uri,
        style_uri,
        style_text,
    )
}

fn run_disk_cache_standalone_session(
    workspace_uri: &str,
    style_uri: &str,
    style_text: &str,
    cache_dir: Option<PathBuf>,
) -> Vec<ScheduledLspOutput> {
    let mut state = LspShellState::default();
    state.configure_standalone_cache_storage(cache_dir);
    run_disk_cache_session_with_state(state, workspace_uri, style_uri, style_text)
}

fn run_disk_cache_session_with_state(
    mut state: LspShellState,
    workspace_uri: &str,
    style_uri: &str,
    style_text: &str,
) -> Vec<ScheduledLspOutput> {
    let initialize_response = handle_lsp_message(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": {
                "workspaceFolders": [
                    {
                        "uri": workspace_uri,
                        "name": "disk-cache",
                    },
                ],
            },
        }),
    );
    assert!(initialize_response.is_some());
    handle_lsp_message_scheduled_outputs(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "method": "initialized",
            "params": {},
        }),
    );
    handle_lsp_message_scheduled_outputs(
        &mut state,
        json!({
            "jsonrpc": "2.0",
            "method": "textDocument/didOpen",
            "params": {
                "textDocument": {
                    "uri": style_uri,
                    "languageId": "scss",
                    "version": 1,
                    "text": style_text,
                },
            },
        }),
    )
}

fn disk_cache_dir(workspace_root: &Path) -> PathBuf {
    workspace_root.join(".cache/omena/diagnostics-cache-v1")
}

fn shard_files(cache_dir: &Path) -> Vec<PathBuf> {
    let Ok(entries) = std::fs::read_dir(cache_dir) else {
        return Vec::new();
    };
    let mut files = entries
        .flatten()
        .map(|entry| entry.path())
        .filter(|path| path.extension().and_then(|extension| extension.to_str()) == Some("json"))
        .collect::<Vec<_>>();
    files.sort();
    files
}

fn cache_files_below(root: &Path) -> Vec<PathBuf> {
    let Ok(entries) = std::fs::read_dir(root) else {
        return Vec::new();
    };
    let mut files = Vec::new();
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            files.extend(cache_files_below(path.as_path()));
        } else if path.is_file()
            && path
                .components()
                .any(|component| component.as_os_str() == "omena")
        {
            files.push(path);
        }
    }
    files.sort();
    files
}

#[test]
fn bridge_storage_consumes_only_the_workspace_recorded_verdict_directory() -> TestResult {
    let workspace_root = disk_cache_workspace_root("recorded-shard-verdict-directory");
    std::fs::create_dir_all(workspace_root.as_path())?;
    let canonical_workspace_root = std::fs::canonicalize(workspace_root.as_path())?;
    let workspace_uri = format!("file://{}", canonical_workspace_root.display());
    let document_uri = format!("{workspace_uri}/src/App.tsx");
    let state = LspShellState::default();
    let storage = crate::external_sif_loader::bridge_cache_storage_for_document(
        &state,
        Some(workspace_uri.as_str()),
        document_uri.as_str(),
    )
    .ok_or_else(|| std::io::Error::other("bridge cache storage"))?;

    assert_eq!(
        storage.recorded_verdict_dir(),
        Some(
            canonical_workspace_root
                .join(".cache/omena")
                .join(omena_sif::OMENA_SIF_SHARD_VERDICT_DIR_V1)
                .as_path()
        )
    );
    let _ = std::fs::remove_dir_all(workspace_root);
    Ok(())
}

#[test]
fn observed_cache_writes_are_contained_by_the_declared_surface() -> TestResult {
    let fixture_root = disk_cache_workspace_root("declared-write-containment");
    let (workspace_uri, style_uri) =
        write_disk_cache_style_fixture(fixture_root.as_path(), DISK_CACHE_STYLE_TEXT);
    let process_environment_root = std::env::var_os("OMENA_CACHE_DIR").map(PathBuf::from);
    let forced_lsp_root = process_environment_root
        .clone()
        .unwrap_or_else(|| fixture_root.join("forced-cache-root"));
    let outputs = run_disk_cache_standalone_session(
        workspace_uri.as_str(),
        style_uri.as_str(),
        DISK_CACHE_STYLE_TEXT,
        process_environment_root
            .is_none()
            .then(|| forced_lsp_root.clone()),
    );
    assert!(
        !outputs.is_empty(),
        "the LSP store pass must produce output"
    );

    let external_package = fixture_root.join("external-package");
    std::fs::create_dir_all(external_package.as_path())?;
    std::fs::write(
        external_package.join("package.json"),
        r#"{"name":"external-package"}"#,
    )?;
    let external_style = external_package.join("tokens.scss");
    std::fs::write(external_style.as_path(), "$brand: #0af;\n")?;
    let bridge_storage = omena_query::OmenaQueryExternalSifStorageV0::from_workspace_cache_root(
        forced_lsp_root
            .join("omena")
            .join("workspaces")
            .join("bridge-fixture"),
    );
    omena_query::generate_omena_bridge_sif_for_resolved_style_path_with_cache_context_and_storage(
        external_style.to_string_lossy().as_ref(),
        &omena_query::OmenaQueryExternalSifCacheContextV0::default(),
        Some(&bridge_storage),
    )?;

    let mut observed_files = cache_files_below(fixture_root.as_path());
    observed_files.extend(cache_files_below(forced_lsp_root.as_path()));
    observed_files.sort();
    observed_files.dedup();
    assert!(
        !observed_files.is_empty(),
        "the store pass must create observable cache files"
    );

    let declared_roots = crate::boundary::declared_cache_write_surfaces_for_rungs(
        crate::CacheStorageRungV0::Environment,
        crate::CacheStorageRungV0::Environment,
    )
    .into_iter()
    .filter_map(|surface| match surface.resolved_rung {
        crate::CacheStorageRungV0::Environment => {
            Some(forced_lsp_root.join("omena").join("workspaces"))
        }
        crate::CacheStorageRungV0::Workspace => match surface.root_kind {
            crate::CacheWriteSurfaceKindV0::LspWorkspaceCache => {
                Some(fixture_root.join(".cache").join("omena"))
            }
            crate::CacheWriteSurfaceKindV0::BridgeExternalSifCache => {
                Some(external_package.join(".cache").join("omena"))
            }
        },
        crate::CacheStorageRungV0::InitializationOptions
        | crate::CacheStorageRungV0::Platform
        | crate::CacheStorageRungV0::Disabled => None,
    })
    .collect::<Vec<_>>();
    println!("cacheContainment observed={observed_files:?} declared={declared_roots:?}");
    assert!(
        observed_files
            .iter()
            .all(|path| declared_roots.iter().any(|root| path.starts_with(root))),
        "observed cache writes must stay inside the declared set: observed={observed_files:?} declared={declared_roots:?}"
    );

    let _ = std::fs::remove_dir_all(fixture_root);
    Ok(())
}

fn serialized_outputs(outputs: &[ScheduledLspOutput]) -> String {
    serde_json::to_string(
        &outputs
            .iter()
            .map(|output| {
                json!({
                    "delayMillis": output.delay_millis,
                    "coalesceKey": output.coalesce_key,
                    "value": output.value,
                })
            })
            .collect::<Vec<_>>(),
    )
    .unwrap_or_default()
}

fn outputs_contain_diagnostic_code(outputs: &[ScheduledLspOutput], code: &str) -> bool {
    outputs.iter().any(|output| {
        output
            .value
            .pointer("/params/diagnostics")
            .and_then(Value::as_array)
            .is_some_and(|diagnostics| {
                diagnostics
                    .iter()
                    .any(|diagnostic| diagnostic.pointer("/code") == Some(&json!(code)))
            })
    })
}

#[test]
fn disk_cache_environment_fingerprint_includes_style_resolution_disk_identity_snapshot()
-> Result<(), &'static str> {
    let style_sources = vec![OmenaQueryStyleSourceInputV0 {
        style_path: "file:///workspace/src/App.module.scss".to_string(),
        style_source: "@use \"@styles/tokens\";".to_string(),
    }];
    let source_documents = Vec::<OmenaQuerySourceDocumentInputV0>::new();
    let external_sifs = Vec::<OmenaQueryExternalSifInputV0>::new();
    let package_manifests = Vec::<OmenaQueryStylePackageManifestV0>::new();
    let base_inputs = omena_query::OmenaQueryStyleResolutionInputsV0::default();
    let disk_backed_inputs = omena_query::OmenaQueryStyleResolutionInputsV0 {
        disk_style_path_identities: vec![
            omena_query::OmenaQueryStyleModuleDiskCandidateIdentityV0 {
                style_path: "/workspace/src/tokens.scss".to_string(),
                metadata_identity: "file|len12|mtime1".to_string(),
            },
        ],
        ..Default::default()
    };

    let plan_for = |resolution_inputs: &omena_query::OmenaQueryStyleResolutionInputsV0| {
        crate::disk_cache::disk_diagnostics_cache_wave_plan_v1(
            &crate::disk_cache::DiskDiagnosticsCacheEnvironmentComponentsV1 {
                style_sources: style_sources.as_slice(),
                source_documents: source_documents.as_slice(),
                package_manifests: package_manifests.as_slice(),
                external_sifs: external_sifs.as_slice(),
                resolution_inputs,
                severity: 2,
                deep_analysis: false,
            },
        )
    };
    let base_plan = plan_for(&base_inputs).ok_or("base plan")?;
    let disk_backed_plan = plan_for(&disk_backed_inputs).ok_or("disk-backed plan")?;
    assert_ne!(
        base_plan.environment_fingerprint_for_test(),
        disk_backed_plan.environment_fingerprint_for_test(),
    );
    Ok(())
}

#[test]
fn first_resolve_writes_shard_and_fresh_state_replays_byte_identical_diagnostics() {
    let workspace_root = disk_cache_workspace_root("replay");
    let (workspace_uri, style_uri) =
        write_disk_cache_style_fixture(&workspace_root, DISK_CACHE_STYLE_TEXT);

    let first_outputs = run_disk_cache_session(
        workspace_uri.as_str(),
        style_uri.as_str(),
        DISK_CACHE_STYLE_TEXT,
    );
    assert!(
        outputs_contain_diagnostic_code(&first_outputs, "missingCustomProperty"),
        "first session must compute real diagnostics",
    );
    let cache_dir = disk_cache_dir(&workspace_root);
    assert_eq!(
        shard_files(&cache_dir).len(),
        1,
        "first resolve must write exactly one shard under {}",
        cache_dir.display(),
    );
    let attribution = workspace_root
        .join(".cache")
        .join("omena")
        .join(".omena-cache-owner.json");
    assert!(
        attribution.is_file(),
        "the diagnostics-only writer must stamp its resolved cache root"
    );

    let second_outputs = run_disk_cache_session(
        workspace_uri.as_str(),
        style_uri.as_str(),
        DISK_CACHE_STYLE_TEXT,
    );
    assert_eq!(
        serialized_outputs(&first_outputs),
        serialized_outputs(&second_outputs),
        "a fresh state with identical inputs must publish byte-equal payloads",
    );
    assert_eq!(
        shard_files(&cache_dir).len(),
        1,
        "an exact-key hit must not write additional shards",
    );
}

#[test]
fn exact_key_hit_serves_diagnostics_from_the_shard_on_disk() -> Result<(), String> {
    let workspace_root = disk_cache_workspace_root("sentinel");
    let (workspace_uri, style_uri) =
        write_disk_cache_style_fixture(&workspace_root, DISK_CACHE_STYLE_TEXT);

    run_disk_cache_session(
        workspace_uri.as_str(),
        style_uri.as_str(),
        DISK_CACHE_STYLE_TEXT,
    );
    let cache_dir = disk_cache_dir(&workspace_root);
    let shards = shard_files(&cache_dir);
    let shard_path = shards.first().ok_or("first session must write a shard")?;

    // Replace the shard payload while keeping schema/key/target intact: the
    // follow-up session publishing the sentinel proves the diagnostics were
    // served from the disk shard rather than recomputed.
    let shard_source =
        std::fs::read_to_string(shard_path).map_err(|error| format!("read shard: {error}"))?;
    let mut shard: Value =
        serde_json::from_str(shard_source.as_str()).map_err(|error| format!("parse: {error}"))?;
    shard["diagnosticsJson"] = json!([
        {
            "range": {
                "start": {"line": 0, "character": 0},
                "end": {"line": 0, "character": 1},
            },
            "severity": 1,
            "code": "diskCacheSentinel",
            "source": "omena-css",
            "message": "served from the tampered shard",
            "data": {},
        },
    ]);
    // The output digest binds the payload to the shard, so the sentinel swap
    // must re-digest its payload (computed independently of the production
    // code path) — and a swap WITHOUT a matching digest must be rejected.
    let sentinel_digest = omena_sif::compute_omena_sif_leaf_hash_v1(
        omena_sif::write_omena_canonical_json_bytes_v1(&shard["diagnosticsJson"])
            .map_err(|error| format!("canonicalize sentinel: {error}"))?
            .as_slice(),
    )
    .as_str()
    .to_string();
    let stale_digest_shard =
        serde_json::to_vec(&shard).map_err(|error| format!("serialize stale: {error}"))?;
    std::fs::write(shard_path, stale_digest_shard)
        .map_err(|error| format!("write stale: {error}"))?;
    let stale_outputs = run_disk_cache_session(
        workspace_uri.as_str(),
        style_uri.as_str(),
        DISK_CACHE_STYLE_TEXT,
    );
    assert!(
        !outputs_contain_diagnostic_code(&stale_outputs, "diskCacheSentinel"),
        "a payload swap without a matching output digest must be rejected",
    );

    shard["outputDigest"] = json!(sentinel_digest);
    let tampered =
        serde_json::to_vec(&shard).map_err(|error| format!("serialize tampered: {error}"))?;
    std::fs::write(shard_path, tampered).map_err(|error| format!("write tampered: {error}"))?;

    let outputs = run_disk_cache_session(
        workspace_uri.as_str(),
        style_uri.as_str(),
        DISK_CACHE_STYLE_TEXT,
    );
    assert!(
        outputs_contain_diagnostic_code(&outputs, "diskCacheSentinel"),
        "an exact key match with a bound digest must serve the shard content from disk",
    );
    assert!(
        !outputs_contain_diagnostic_code(&outputs, "missingCustomProperty"),
        "a shard hit must not recompute diagnostics",
    );
    Ok(())
}

#[test]
fn edited_document_text_misses_the_shard_and_recomputes() -> Result<(), String> {
    let workspace_root = disk_cache_workspace_root("miss");
    let (workspace_uri, style_uri) =
        write_disk_cache_style_fixture(&workspace_root, DISK_CACHE_STYLE_TEXT);

    run_disk_cache_session(
        workspace_uri.as_str(),
        style_uri.as_str(),
        DISK_CACHE_STYLE_TEXT,
    );
    let cache_dir = disk_cache_dir(&workspace_root);
    let shards = shard_files(&cache_dir);
    let shard_path = shards.first().ok_or("first session must write a shard")?;
    let shard_source =
        std::fs::read_to_string(shard_path).map_err(|error| format!("read shard: {error}"))?;
    let mut shard: Value =
        serde_json::from_str(shard_source.as_str()).map_err(|error| format!("parse: {error}"))?;
    shard["diagnosticsJson"] = json!([{"code": "diskCacheSentinel"}]);
    let tampered =
        serde_json::to_vec(&shard).map_err(|error| format!("serialize tampered: {error}"))?;
    std::fs::write(shard_path, tampered).map_err(|error| format!("write tampered: {error}"))?;

    // Different buffer text => the recorded target dependency's content hash
    // no longer verifies => the tampered shard must be ignored, the
    // diagnostics recomputed, and the SAME stable address overwritten in
    // place (stage 2: one shard per target, no accumulation).
    let edited_text = ":root { --brand: red; }\n.btn { width: var(--missing); }";
    let outputs = run_disk_cache_session(workspace_uri.as_str(), style_uri.as_str(), edited_text);
    assert!(
        !outputs_contain_diagnostic_code(&outputs, "diskCacheSentinel"),
        "an edited document must not serve the stale shard",
    );
    assert!(
        outputs_contain_diagnostic_code(&outputs, "missingCustomProperty"),
        "an edited document must recompute real diagnostics",
    );
    assert_eq!(
        shard_files(&cache_dir).len(),
        1,
        "the recompute must overwrite the target's single shard in place",
    );
    Ok(())
}