lsp-max 26.7.3

Law-state LSP runtime: max LSP 3.18 coverage, process-mining conformance, receipt-chain admission
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
//! Smoke-level integration tests for the 15 max/ RPC methods that previously had
//! zero test coverage.
//!
//! Each test: boot server → send request → assert response has 'result' key (not 'error').
//! This prevents silent regressions when dispatch branches are refactored.

use lsp_max::{LanguageServer, LspService, Server};
use std::sync::Arc;
use std::time::Duration;

static TEST_MUTEX: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

use lsp_max::jsonrpc::Result as RpcResult;
use lsp_max::lsp_types as lsp;

mod common;
use common::{cleanup_receipts, read_message, wait_for_response, write_msg, RxLog, TxShared};

struct TestBackend;

#[lsp_max::async_trait]
impl LanguageServer for TestBackend {
    async fn initialize(&self, _: lsp::InitializeParams) -> RpcResult<lsp::InitializeResult> {
        Ok(lsp::InitializeResult::default())
    }
    async fn shutdown(&self) -> RpcResult<()> {
        Ok(())
    }
}

type SerialGuard = tokio::sync::MutexGuard<'static, ()>;

async fn boot_server() -> (TxShared, RxLog, tokio::task::JoinHandle<()>, SerialGuard) {
    let _guard = TEST_MUTEX.lock().await;
    lsp_max::reset_registry_for_tests();
    let temp_dir = tempfile::tempdir().unwrap();
    let temp_path = temp_dir.path().to_path_buf();
    std::boxed::Box::leak(std::boxed::Box::new(temp_dir));
    if let Ok(mut reg) = lsp_max::get_registry().lock() {
        reg.root_path = temp_path.clone();
    }
    let _ = std::fs::remove_file(temp_path.join("admission.receipt"));
    let _ = std::fs::remove_file(temp_path.join("security.receipt"));
    let _ = std::fs::remove_file(temp_path.join("auth.receipt"));

    let (service, socket) = LspService::new(|_| TestBackend);
    let (client_tx, server_rx) = tokio::io::duplex(1024 * 1024);
    let (server_tx, client_rx) = tokio::io::duplex(1024 * 1024);

    let server_handle = tokio::spawn(async move {
        let _ = Server::new(server_rx, server_tx, socket)
            .serve(service)
            .await;
    });

    let client_tx_shared: TxShared = Arc::new(tokio::sync::Mutex::new(Some(client_tx)));
    let received: RxLog = Arc::new(std::sync::Mutex::new(Vec::new()));
    let received_clone = received.clone();

    let mut client_rx_owned = client_rx;
    tokio::spawn(async move {
        while let Ok(msg) = read_message(&mut client_rx_owned).await {
            received_clone.lock().unwrap().push(msg);
        }
    });

    write_msg(
        &client_tx_shared,
        serde_json::json!({"jsonrpc":"2.0","id":0,"method":"initialize","params":{"capabilities":{}}}),
    )
    .await;
    wait_for_response(received.clone(), 0, Duration::from_millis(300)).await;

    (client_tx_shared, received, server_handle, _guard)
}

fn assert_has_result(resp: &serde_json::Value, method: &str) {
    assert!(
        resp.get("result").is_some(),
        "method {} must return 'result', got: {}",
        method,
        resp
    );
}

async fn test_rpc_method(method: &str, params: serde_json::Value) -> serde_json::Value {
    let (tx, rx, _h, _guard) = boot_server().await;
    let payload = if params.is_null() {
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": method
        })
    } else {
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": method,
            "params": params
        })
    };
    write_msg(&tx, payload).await;
    let resp = wait_for_response(rx, 1, Duration::from_millis(300)).await;
    cleanup_receipts();
    resp
}

// ---------------------------------------------------------------------------
// max/hook
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "current_thread")]
async fn test_max_hook_returns_result() {
    let resp = test_rpc_method("max/hook", serde_json::Value::Null).await;
    assert_has_result(&resp, "max/hook");
}

// ---------------------------------------------------------------------------
// max/hookGraph
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "current_thread")]
async fn test_max_hook_graph_returns_result() {
    let resp = test_rpc_method("max/hookGraph", serde_json::Value::Null).await;
    assert_has_result(&resp, "max/hookGraph");
}

// ---------------------------------------------------------------------------
// max/chain
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "current_thread")]
async fn test_max_chain_returns_result() {
    let resp = test_rpc_method("max/chain", serde_json::Value::Null).await;
    assert_has_result(&resp, "max/chain");
}

// ---------------------------------------------------------------------------
// max/propagate
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "current_thread")]
async fn test_max_propagate_returns_result() {
    let resp = test_rpc_method(
        "max/propagate",
        serde_json::json!({
            "receipt_id": "rcpt-propagate-test",
            "hash": "abc123",
            "prev_receipt_hash": null
        }),
    )
    .await;
    assert_has_result(&resp, "max/propagate");
}

// ---------------------------------------------------------------------------
// max/autonomicLoop
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "current_thread")]
async fn test_max_autonomic_loop_returns_result() {
    let resp = test_rpc_method("max/autonomicLoop", serde_json::Value::Null).await;
    assert_has_result(&resp, "max/autonomicLoop");
}

// ---------------------------------------------------------------------------
// max/manifoldSnapshot
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "current_thread")]
async fn test_max_manifold_snapshot_returns_result() {
    let resp = test_rpc_method("max/manifoldSnapshot", serde_json::Value::Null).await;
    assert_has_result(&resp, "max/manifoldSnapshot");
}

// ---------------------------------------------------------------------------
// max/lawfulTransition
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "current_thread")]
async fn test_max_lawful_transition_returns_result() {
    let resp = test_rpc_method("max/lawfulTransition", serde_json::json!("Initializing")).await;
    assert_has_result(&resp, "max/lawfulTransition");
}

// ---------------------------------------------------------------------------
// max/admission
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "current_thread")]
async fn test_max_admission_returns_result() {
    let resp = test_rpc_method("max/admission", serde_json::Value::Null).await;
    assert_has_result(&resp, "max/admission");
    let result = resp.get("result").unwrap();
    let verdict = result.get("verdict").and_then(|v| v.as_str()).unwrap_or("");
    assert!(
        ["Admitted", "Refused", "Unknown"].contains(&verdict),
        "verdict must be Admitted/Refused/Unknown, got: {}",
        verdict
    );
}

// ---------------------------------------------------------------------------
// max/refusal
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "current_thread")]
async fn test_max_refusal_returns_result() {
    let resp = test_rpc_method("max/refusal", serde_json::json!("diag-test-refusal")).await;
    assert_has_result(&resp, "max/refusal");
}

// ---------------------------------------------------------------------------
// max/replay
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "current_thread")]
async fn test_max_replay_returns_result() {
    let resp = test_rpc_method("max/replay", serde_json::Value::Null).await;
    assert_has_result(&resp, "max/replay");
    let result = resp.get("result").unwrap();
    assert!(
        result.get("receipt_count").is_some(),
        "max/replay result must have 'receipt_count' key, got: {}",
        result
    );
    assert!(
        result.get("receipts").is_some(),
        "max/replay result must have 'receipts' key, got: {}",
        result
    );
}

// ---------------------------------------------------------------------------
// max/releaseActuation — may succeed or return an error if diagnostics block;
// either way the transport must return a well-formed JSON-RPC response.
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "current_thread")]
async fn test_max_release_actuation_returns_rpc_response() {
    let resp = test_rpc_method("max/releaseActuation", serde_json::Value::Null).await;
    assert!(
        resp.get("result").is_some() || resp.get("error").is_some(),
        "max/releaseActuation must return a JSON-RPC response, got: {}",
        resp
    );
}

// ---------------------------------------------------------------------------
// max/dumpState — DfLSS CTQ: result must contain 'diagnostics' field
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "current_thread")]
async fn test_max_dump_state_returns_result() {
    let resp = test_rpc_method("max/dumpState", serde_json::Value::Null).await;
    assert_has_result(&resp, "max/dumpState");
    let result = resp.get("result").unwrap();
    assert!(
        result.get("diagnostics").is_some(),
        "max/dumpState result must contain 'diagnostics' field (ServerRegistry), got: {}",
        result
    );
}

// ---------------------------------------------------------------------------
// max/restoreState — dump first, then restore the same state
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "current_thread")]
async fn test_max_restore_state_returns_result() {
    let (tx, rx, _h, _guard) = boot_server().await;

    // First dump to get a valid state object
    write_msg(
        &tx,
        serde_json::json!({"jsonrpc":"2.0","id":1,"method":"max/dumpState"}),
    )
    .await;
    let dump_resp = wait_for_response(rx.clone(), 1, Duration::from_millis(300)).await;
    let state = dump_resp
        .get("result")
        .expect("dumpState must return result")
        .clone();

    // Now restore it
    write_msg(
        &tx,
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": 2,
            "method": "max/restoreState",
            "params": state
        }),
    )
    .await;
    let resp = wait_for_response(rx, 2, Duration::from_millis(300)).await;
    assert_has_result(&resp, "max/restoreState");
    cleanup_receipts();
}

// ---------------------------------------------------------------------------
// max/reset
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "current_thread")]
async fn test_max_reset_returns_result() {
    let resp = test_rpc_method("max/reset", serde_json::Value::Null).await;
    assert_has_result(&resp, "max/reset");
}

// ---------------------------------------------------------------------------
// DfLSS CTQ: max/lawfulTransition — verify "admitted" boolean in result
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "current_thread")]
async fn test_max_lawful_transition_has_admitted_field() {
    let resp = test_rpc_method("max/lawfulTransition", serde_json::json!("Initializing")).await;
    assert_has_result(&resp, "max/lawfulTransition");
    let result = resp.get("result").unwrap();
    assert!(
        result.get("admitted").is_some(),
        "max/lawfulTransition result must have 'admitted' field, got: {}",
        result
    );
    let admitted = result.get("admitted").unwrap();
    assert!(
        admitted.is_boolean(),
        "max/lawfulTransition 'admitted' must be a boolean, got: {}",
        admitted
    );
    assert!(
        result.get("current_phase").is_some(),
        "max/lawfulTransition result must have 'current_phase' field"
    );
    assert!(
        result.get("requested_phase").is_some(),
        "max/lawfulTransition result must have 'requested_phase' field"
    );
}

// ---------------------------------------------------------------------------
// DfLSS CTQ: max/admission — verify ConformanceVector fields
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "current_thread")]
async fn test_max_admission_conformance_vector_fields() {
    let resp = test_rpc_method("max/admission", serde_json::Value::Null).await;
    assert_has_result(&resp, "max/admission");
    let result = resp.get("result").unwrap();
    // The verdict must be one of the three ConformanceVector states
    let verdict = result.get("verdict").and_then(|v| v.as_str()).unwrap_or("");
    assert!(
        ["Admitted", "Refused", "Unknown"].contains(&verdict),
        "max/admission verdict must be Admitted/Refused/Unknown (ConformanceVector states), got: {}",
        verdict
    );
    // diagnostic_count is a required field
    assert!(
        result.get("diagnostic_count").is_some(),
        "max/admission result must have 'diagnostic_count' field"
    );
}

// ---------------------------------------------------------------------------
// DfLSS CTQ: max/refusal — verify response shape with refused/receipt fields
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "current_thread")]
async fn test_max_refusal_response_shape() {
    let resp = test_rpc_method("max/refusal", serde_json::json!("diag-ctq-refusal")).await;
    assert_has_result(&resp, "max/refusal");
    let result = resp.get("result").unwrap();
    assert!(
        result.get("refused").is_some(),
        "max/refusal result must have 'refused' field, got: {}",
        result
    );
    let refused = result.get("refused").unwrap().as_bool().unwrap_or(false);
    assert!(refused, "max/refusal 'refused' must be true");
    assert!(
        result.get("diagnostic_id").is_some(),
        "max/refusal result must have 'diagnostic_id' field"
    );
    assert!(
        result.get("receipt").is_some(),
        "max/refusal result must have 'receipt' field"
    );
    let receipt = result.get("receipt").unwrap();
    assert!(
        receipt.get("receipt_id").is_some(),
        "max/refusal receipt must have 'receipt_id' field"
    );
    assert!(
        receipt.get("hash").is_some(),
        "max/refusal receipt must have 'hash' field"
    );
}

// ---------------------------------------------------------------------------
// max/conformanceDelta
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "current_thread")]
async fn test_max_conformance_delta_returns_result() {
    let resp = test_rpc_method(
        "max/conformanceDelta",
        serde_json::json!({ "since_seq": 0 }),
    )
    .await;
    assert_has_result(&resp, "max/conformanceDelta");
    let result = resp.get("result").unwrap();
    assert!(
        result.get("deltas").is_some(),
        "conformanceDelta result must have 'deltas' key"
    );
    assert!(
        result.get("current_seq").is_some(),
        "conformanceDelta result must have 'current_seq' key"
    );
}

// ---------------------------------------------------------------------------
// Full lifecycle: initialize → diagnostic → repair → conformance → release
// Tests the complete customer-facing value path end-to-end across the
// JSON-RPC transport boundary.
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "current_thread")]
async fn test_full_lifecycle_diagnostic_repair_conformance_release() {
    let (tx, rx, _h, _guard) = boot_server().await;

    // Step 1: snapshot to materialize current diagnostics.
    // On a fresh boot, auth.receipt does not exist so diag-auth-generator is present.
    write_msg(
        &tx,
        serde_json::json!({"jsonrpc":"2.0","id":10,"method":"max/snapshot"}),
    )
    .await;
    let snap1_resp = wait_for_response(rx.clone(), 10, Duration::from_millis(300)).await;
    assert!(
        snap1_resp.get("result").is_some(),
        "max/snapshot (step 1) must return 'result', got: {}",
        snap1_resp
    );
    let snapshot_id1 = {
        let raw = &snap1_resp["result"];
        if let Some(s) = raw.as_str() {
            s.to_string()
        } else if let Some(s) = raw.get("id").and_then(|v| v.as_str()) {
            s.to_string()
        } else {
            raw.to_string().trim_matches('"').to_string()
        }
    };
    assert!(
        snapshot_id1.starts_with("snap-"),
        "Expected snapshot_id to start with 'snap-', got: {}",
        snapshot_id1
    );

    // Step 2: retrieve conformance vector for the initial snapshot.
    write_msg(
        &tx,
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": 11,
            "method": "max/conformanceVector",
            "params": snapshot_id1
        }),
    )
    .await;
    let cv1_resp = wait_for_response(rx.clone(), 11, Duration::from_millis(300)).await;
    assert!(
        cv1_resp.get("result").is_some(),
        "max/conformanceVector (initial) must return 'result', got: {}",
        cv1_resp
    );
    // After initialize, diag-uninitialized-admission is suppressed (state != Uninitialized).
    // Only INFORMATION/WARNING diagnostics are active (auth-generator, missing-receipt).
    // Verify the conformance vector has the expected structure.
    assert!(
        cv1_resp["result"].get("admitted").is_some(),
        "conformanceVector must have 'admitted' field, got cv: {}",
        cv1_resp["result"]
    );
    assert!(
        cv1_resp["result"].get("refused").is_some(),
        "conformanceVector must have 'refused' field, got cv: {}",
        cv1_resp["result"]
    );

    // Step 3: explain the auth-generator diagnostic (INFORMATION, no preconditions).
    write_msg(
        &tx,
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": 12,
            "method": "max/explainDiagnostic",
            "params": "diag-auth-generator"
        }),
    )
    .await;
    let explain_resp = wait_for_response(rx.clone(), 12, Duration::from_millis(300)).await;
    assert!(
        explain_resp.get("result").is_some(),
        "max/explainDiagnostic must return 'result', got: {}",
        explain_resp
    );
    assert_eq!(
        explain_resp["result"]["diagnostic_id"]
            .as_str()
            .unwrap_or(""),
        "diag-auth-generator",
        "explainDiagnostic must return the requested diagnostic"
    );

    // Step 4: retrieve repair plan for the auth-generator diagnostic.
    write_msg(
        &tx,
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": 13,
            "method": "max/repairPlan",
            "params": "diag-auth-generator"
        }),
    )
    .await;
    let plan_resp = wait_for_response(rx.clone(), 13, Duration::from_millis(300)).await;
    assert!(
        plan_resp.get("result").is_some(),
        "max/repairPlan must return 'result', got: {}",
        plan_resp
    );
    let plans = plan_resp["result"]
        .as_array()
        .expect("repairPlan must return array");
    assert!(
        !plans.is_empty(),
        "repairPlan for diag-auth-generator must return at least one action"
    );
    let action = plans[0].clone();

    // Step 5: apply the repair transaction (no preconditions on auth-generator action).
    write_msg(
        &tx,
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": 14,
            "method": "max/applyRepairTransaction",
            "params": action
        }),
    )
    .await;
    let repair_resp = wait_for_response(rx.clone(), 14, Duration::from_millis(300)).await;
    assert!(
        repair_resp.get("result").is_some(),
        "max/applyRepairTransaction must return 'result', got: {}",
        repair_resp
    );
    let receipt_id = repair_resp["result"]["receipt_id"].as_str().unwrap_or("");
    assert!(
        receipt_id.starts_with("rcpt-"),
        "repair receipt_id must start with 'rcpt-', got: {}",
        repair_resp["result"]
    );

    // Step 6: take a second snapshot to capture post-repair state.
    write_msg(
        &tx,
        serde_json::json!({"jsonrpc":"2.0","id":15,"method":"max/snapshot"}),
    )
    .await;
    let snap2_resp = wait_for_response(rx.clone(), 15, Duration::from_millis(300)).await;
    assert!(
        snap2_resp.get("result").is_some(),
        "max/snapshot (post-repair) must return 'result', got: {}",
        snap2_resp
    );
    let snapshot_id2 = {
        let raw = &snap2_resp["result"];
        if let Some(s) = raw.as_str() {
            s.to_string()
        } else if let Some(s) = raw.get("id").and_then(|v| v.as_str()) {
            s.to_string()
        } else {
            raw.to_string().trim_matches('"').to_string()
        }
    };
    assert!(
        snapshot_id2.starts_with("snap-"),
        "Expected second snapshot_id to start with 'snap-', got: {}",
        snapshot_id2
    );

    // Step 7: retrieve conformance vector for post-repair snapshot and verify fields.
    write_msg(
        &tx,
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": 16,
            "method": "max/conformanceVector",
            "params": snapshot_id2
        }),
    )
    .await;
    let cv2_resp = wait_for_response(rx.clone(), 16, Duration::from_millis(300)).await;
    assert!(
        cv2_resp.get("result").is_some(),
        "max/conformanceVector (post-repair) must return 'result', got: {}",
        cv2_resp
    );
    let cv2 = &cv2_resp["result"];
    assert!(
        cv2.get("admitted").is_some(),
        "post-repair conformanceVector must have 'admitted' field"
    );
    assert!(
        cv2.get("refused").is_some(),
        "post-repair conformanceVector must have 'refused' field"
    );

    // Step 8: releaseActuation - must return a well-formed JSON-RPC response.
    // It may succeed or error (no active instance for this id), but transport must be sound.
    write_msg(
        &tx,
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": 17,
            "method": "max/releaseActuation",
            "params": { "instance_id": "lifecycle-test-instance" }
        }),
    )
    .await;
    let release_resp = wait_for_response(rx.clone(), 17, Duration::from_millis(300)).await;
    assert!(
        release_resp.get("result").is_some() || release_resp.get("error").is_some(),
        "max/releaseActuation must return a well-formed JSON-RPC response, got: {}",
        release_resp
    );

    cleanup_receipts();
}