lemma 0.9.2

A pure, declarative language for business rules.
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
use std::net::TcpStream;
use std::time::{Duration, Instant};

const SERVER_TEST_PORT: u16 = 19998;
const SERVER_STARTUP_TIMEOUT: Duration = Duration::from_secs(30);

fn wait_for_port(port: u16, timeout: Duration) -> bool {
    let deadline = Instant::now() + timeout;
    while Instant::now() < deadline {
        if TcpStream::connect(("127.0.0.1", port)).is_ok() {
            return true;
        }
        std::thread::sleep(Duration::from_millis(50));
    }
    false
}

#[test]
fn test_get_spec_route_returns_200() {
    let temp_dir = tempfile::tempdir().unwrap();
    let lemma_file = temp_dir.path().join("single.lemma");
    std::fs::write(
        &lemma_file,
        r#"spec single_spec
data x: number
rule result: x
"#,
    )
    .unwrap();

    let bin = env!("CARGO_BIN_EXE_lemma");
    let mut child = std::process::Command::new(bin)
        .arg("server")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("--port")
        .arg(SERVER_TEST_PORT.to_string())
        .spawn()
        .unwrap();

    let ok = wait_for_port(SERVER_TEST_PORT, SERVER_STARTUP_TIMEOUT);
    if !ok {
        let _ = child.kill();
        let _ = child.wait();
        panic!("server did not start within timeout");
    }

    let url = format!("http://127.0.0.1:{}/single_spec?x=42", SERVER_TEST_PORT);
    let resp = reqwest::blocking::get(&url).expect("GET request");
    let status = resp.status();
    let _ = child.kill();
    let _ = child.wait();

    assert!(
        status.is_success(),
        "GET /single_spec should return 2xx, got {}",
        status
    );
}

#[test]
fn test_get_with_x_explanations_header_returns_explanation_when_explanations_enabled() {
    let temp_dir = tempfile::tempdir().unwrap();
    let lemma_file = temp_dir.path().join("single.lemma");
    std::fs::write(
        &lemma_file,
        r#"spec single_spec
data x: number
rule result: x
"#,
    )
    .unwrap();

    let port = SERVER_TEST_PORT + 1;
    let bin = env!("CARGO_BIN_EXE_lemma");
    let mut child = std::process::Command::new(bin)
        .arg("server")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("--port")
        .arg(port.to_string())
        .arg("--explanations")
        .spawn()
        .unwrap();

    let ok = wait_for_port(port, SERVER_STARTUP_TIMEOUT);
    if !ok {
        let _ = child.kill();
        let _ = child.wait();
        panic!("server did not start within timeout");
    }

    let client = reqwest::blocking::Client::new();
    let url = format!("http://127.0.0.1:{}/single_spec", port);
    let resp = client
        .post(&url)
        .header("x-explanations", "true")
        .header("Content-Type", "application/json")
        .body(r#"{"x":"42"}"#)
        .send()
        .expect("POST request");
    let status = resp.status();
    let body: serde_json::Value =
        serde_json::from_str(&resp.text().expect("response body")).expect("JSON body");
    let _ = child.kill();
    let _ = child.wait();

    assert!(
        status.is_success(),
        "POST with x-explanations should return 2xx, got {}",
        status
    );
    let results = body
        .get("results")
        .expect("response should have envelope 'results' key");
    let rule_result = results
        .get("result")
        .expect("results should have 'result' rule");
    assert!(
        rule_result.get("explanation").is_some(),
        "response should include explanation when x-explanations header sent: {:?}",
        body
    );
    assert_eq!(rule_result["number"].as_str(), Some("42"));
    assert!(body.get("spec").is_some(), "envelope should include spec");
}

#[test]
fn post_evaluate_accept_datetime_selects_temporal_version() {
    let temp_dir = tempfile::tempdir().unwrap();
    std::fs::write(
        temp_dir.path().join("temporal.lemma"),
        r#"spec pricing 2025-01-01
data base: 10
rule total: base

spec pricing 2026-01-01
data base: 99
rule total: base
"#,
    )
    .unwrap();

    let port = SERVER_TEST_PORT + 2;
    let bin = env!("CARGO_BIN_EXE_lemma");
    let mut child = std::process::Command::new(bin)
        .arg("server")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("--port")
        .arg(port.to_string())
        .spawn()
        .unwrap();

    let ok = wait_for_port(port, SERVER_STARTUP_TIMEOUT);
    if !ok {
        let _ = child.kill();
        let _ = child.wait();
        panic!("server did not start within timeout");
    }

    let client = reqwest::blocking::Client::new();
    let url = format!("http://127.0.0.1:{}/pricing", port);

    let post = |accept_dt: &str| -> serde_json::Value {
        let resp = client
            .post(&url)
            .header("Accept-Datetime", accept_dt)
            .header("Content-Type", "application/json")
            .body("{}")
            .send()
            .expect("POST");
        let text = resp.text().expect("body");
        serde_json::from_str(&text).unwrap_or_else(|e| {
            panic!("invalid JSON: {e}; body: {text}");
        })
    };

    let j2025 = post("2025-06-01");
    let j2026 = post("2026-06-01");
    let _ = child.kill();
    let _ = child.wait();

    assert_eq!(
        j2025["results"]["total"]["number"].as_str(),
        Some("10"),
        "Accept-Datetime 2025 should resolve pricing v1: {j2025:?}"
    );
    assert_eq!(
        j2026["results"]["total"]["number"].as_str(),
        Some("99"),
        "Accept-Datetime 2026 should resolve pricing v2: {j2026:?}"
    );
}

#[test]
fn post_evaluate_form_urlencoded_body() {
    let temp_dir = tempfile::tempdir().unwrap();
    std::fs::write(
        temp_dir.path().join("single.lemma"),
        r#"spec single_spec
data x: number
rule result: x
"#,
    )
    .unwrap();

    let port = SERVER_TEST_PORT + 4;
    let bin = env!("CARGO_BIN_EXE_lemma");
    let mut child = std::process::Command::new(bin)
        .arg("server")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("--port")
        .arg(port.to_string())
        .spawn()
        .unwrap();

    let ok = wait_for_port(port, SERVER_STARTUP_TIMEOUT);
    if !ok {
        let _ = child.kill();
        let _ = child.wait();
        panic!("server did not start within timeout");
    }

    let client = reqwest::blocking::Client::new();
    let url = format!("http://127.0.0.1:{}/single_spec", port);
    let resp = client
        .post(&url)
        .header("Content-Type", "application/x-www-form-urlencoded")
        .body("x=42")
        .send()
        .expect("POST request");
    let status = resp.status();
    let body: serde_json::Value =
        serde_json::from_str(&resp.text().expect("response body")).expect("JSON body");
    let _ = child.kill();
    let _ = child.wait();

    assert!(
        status.is_success(),
        "POST form body should return 2xx, got {status}: {body:?}"
    );
    assert_eq!(body["results"]["result"]["number"].as_str(), Some("42"));
}

/// GET `/` returns the same JSON as [`Engine::list`]: workspace and dependency
/// repositories with listed spec rows (name, optional effective_from/effective_to).
/// Temporal show failures belong on GET `/{spec}`, not on the list route.
#[test]
fn list_returns_engine_list_api() {
    let temp_dir = tempfile::tempdir().unwrap();
    std::fs::write(
        temp_dir.path().join("specs.lemma"),
        r#"spec always_available
data x: number
rule result: x

spec future_only 2030-01-01
data y: number
rule result: y
"#,
    )
    .unwrap();

    let port = SERVER_TEST_PORT + 5;
    let bin = env!("CARGO_BIN_EXE_lemma");
    let mut child = std::process::Command::new(bin)
        .arg("server")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("--port")
        .arg(port.to_string())
        .spawn()
        .unwrap();

    let ok = wait_for_port(port, SERVER_STARTUP_TIMEOUT);
    if !ok {
        let _ = child.kill();
        let _ = child.wait();
        panic!("server did not start within timeout");
    }

    let url = format!("http://127.0.0.1:{}/", port);
    let resp = reqwest::blocking::get(&url).expect("GET request");
    let status = resp.status();
    let body_text = resp.text().expect("response body");
    let _ = child.kill();
    let _ = child.wait();

    assert!(
        status.is_success(),
        "GET / should return 2xx, got {status}: {body_text}"
    );
    let body: serde_json::Value = serde_json::from_str(&body_text)
        .unwrap_or_else(|e| panic!("invalid JSON: {e}; {body_text}"));
    let repositories = body
        .as_array()
        .unwrap_or_else(|| panic!("list response must be ResolvedRepository[]: {body}"));

    let workspace = repositories
        .iter()
        .find(|r| r.get("repository").is_none_or(|v| v.is_null()))
        .unwrap_or_else(|| panic!("workspace repository group missing: {body}"));
    let spec_names: Vec<&str> = workspace["specs"]
        .as_array()
        .expect("workspace specs array")
        .iter()
        .filter_map(|row| row["name"].as_str())
        .collect();
    assert!(
        spec_names.contains(&"always_available"),
        "always_available must appear in list: {body}"
    );
    assert!(
        spec_names.contains(&"future_only"),
        "future_only must appear in list regardless of effective instant: {body}"
    );
}

/// GET `/{spec}` before a spec's effective_from must fail (temporal show error),
/// not disappear from GET `/`.
#[test]
fn get_show_before_effective_from_returns_error() {
    let temp_dir = tempfile::tempdir().unwrap();
    std::fs::write(
        temp_dir.path().join("specs.lemma"),
        r#"spec future_only 2030-01-01
data y: number
rule result: y
"#,
    )
    .unwrap();

    let port = SERVER_TEST_PORT + 9;
    let bin = env!("CARGO_BIN_EXE_lemma");
    let mut child = std::process::Command::new(bin)
        .arg("server")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("--port")
        .arg(port.to_string())
        .spawn()
        .unwrap();

    let ok = wait_for_port(port, SERVER_STARTUP_TIMEOUT);
    if !ok {
        let _ = child.kill();
        let _ = child.wait();
        panic!("server did not start within timeout");
    }

    let client = reqwest::blocking::Client::new();
    let url = format!("http://127.0.0.1:{}/future_only", port);
    let resp = client
        .get(&url)
        .header("Accept-Datetime", "2025-06-01")
        .send()
        .expect("GET request");
    let status = resp.status();
    let body_text = resp.text().expect("response body");
    let _ = child.kill();
    let _ = child.wait();

    assert!(
        !status.is_success(),
        "GET /future_only before effective_from must not return 2xx, got {status}: {body_text}"
    );
    let body: serde_json::Value = serde_json::from_str(&body_text)
        .unwrap_or_else(|e| panic!("invalid JSON: {e}; {body_text}"));
    assert!(
        body.get("error").is_some(),
        "show failure must carry error field: {body}"
    );
}

/// By default the server sends no CORS headers: cross-origin browser
/// requests are denied. `--cors` opts in to permissive CORS.
#[test]
fn cors_denied_by_default_and_enabled_with_flag() {
    let temp_dir = tempfile::tempdir().unwrap();
    std::fs::write(
        temp_dir.path().join("single.lemma"),
        r#"spec single_spec
data x: number
rule result: x
"#,
    )
    .unwrap();

    let bin = env!("CARGO_BIN_EXE_lemma");
    let run_case = |port: u16, cors_flag: bool| -> Option<String> {
        let mut cmd = std::process::Command::new(bin);
        cmd.arg("server")
            .arg("--prefix")
            .arg(temp_dir.path())
            .arg("--port")
            .arg(port.to_string());
        if cors_flag {
            cmd.arg("--cors");
        }
        let mut child = cmd.spawn().unwrap();

        let ok = wait_for_port(port, SERVER_STARTUP_TIMEOUT);
        if !ok {
            let _ = child.kill();
            let _ = child.wait();
            panic!("server did not start within timeout");
        }

        let client = reqwest::blocking::Client::new();
        let resp = client
            .get(format!("http://127.0.0.1:{port}/health"))
            .header("Origin", "https://evil.example")
            .send()
            .expect("GET request");
        let allow_origin = resp
            .headers()
            .get("access-control-allow-origin")
            .and_then(|v| v.to_str().ok())
            .map(|s| s.to_string());
        let _ = child.kill();
        let _ = child.wait();
        allow_origin
    };

    let default_origin = run_case(SERVER_TEST_PORT + 6, false);
    assert!(
        default_origin.is_none(),
        "default must not send Access-Control-Allow-Origin, got {default_origin:?}"
    );

    let opt_in_origin = run_case(SERVER_TEST_PORT + 7, true);
    assert_eq!(
        opt_in_origin.as_deref(),
        Some("*"),
        "--cors must send permissive Access-Control-Allow-Origin"
    );
}

/// `--eval-timeout 0` makes every evaluation exceed the wall-clock budget;
/// the server must answer 503 with a JSON error instead of hanging.
/// The spec carries a long rule chain so plan+eval take real work and the
/// zero-length budget always elapses before the blocking task finishes.
#[test]
fn evaluation_timeout_returns_503() {
    let temp_dir = tempfile::tempdir().unwrap();
    let mut spec = String::from("spec slow_spec\ndata x: number\nrule r0: x + 1\n");
    for i in 1..100 {
        spec.push_str(&format!("rule r{i}: r{} * 2 + {i}\n", i - 1));
    }
    std::fs::write(temp_dir.path().join("slow.lemma"), spec).unwrap();

    let port = SERVER_TEST_PORT + 8;
    let bin = env!("CARGO_BIN_EXE_lemma");
    let mut child = std::process::Command::new(bin)
        .arg("server")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("--port")
        .arg(port.to_string())
        .arg("--eval-timeout")
        .arg("0")
        .spawn()
        .unwrap();

    let ok = wait_for_port(port, SERVER_STARTUP_TIMEOUT);
    if !ok {
        let _ = child.kill();
        let _ = child.wait();
        panic!("server did not start within timeout");
    }

    let client = reqwest::blocking::Client::new();
    let resp = client
        .post(format!("http://127.0.0.1:{port}/slow_spec"))
        .header("Content-Type", "application/json")
        .body(r#"{"x":"42"}"#)
        .send()
        .expect("POST request");
    let status = resp.status();
    let body: serde_json::Value =
        serde_json::from_str(&resp.text().expect("response body")).expect("JSON body");
    let _ = child.kill();
    let _ = child.wait();

    assert_eq!(
        status.as_u16(),
        503,
        "zero timeout must yield 503, got {status}: {body:?}"
    );
    assert!(
        body["error"]
            .as_str()
            .expect("error message present")
            .contains("timed out"),
        "error must mention timeout: {body:?}"
    );
}

/// Parse the `YYYY-MM-DD` prefix of an ISO-8601 date string API field.
/// Temporal fields in the public API are always ISO strings, never objects
/// (see `engine/tests/temporal_api_shape.rs`).
fn json_date_ymd(v: &serde_json::Value) -> Option<(i64, u64, u64)> {
    let s = v.as_str()?;
    let (year, rest) = s.split_once('-')?;
    let (month, day) = rest.split_once('-')?;
    Some((year.parse().ok()?, month.parse().ok()?, day.parse().ok()?))
}

/// GET `/{spec}` must expose each temporal version's half-open
/// `[effective_from, effective_to)` range. The latest version's `effective_to`
/// is `null` (no successor); earlier versions' `effective_to` equals the next
/// version's `effective_from`.
#[test]
fn get_show_versions_expose_effective_to_range() {
    let temp_dir = tempfile::tempdir().unwrap();
    std::fs::write(
        temp_dir.path().join("temporal.lemma"),
        r#"spec pricing 2025-01-01
data base: 10
rule total: base

spec pricing 2026-01-01
data base: 99
rule total: base
"#,
    )
    .unwrap();

    let port = SERVER_TEST_PORT + 3;
    let bin = env!("CARGO_BIN_EXE_lemma");
    let mut child = std::process::Command::new(bin)
        .arg("server")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("--port")
        .arg(port.to_string())
        .spawn()
        .unwrap();

    let ok = wait_for_port(port, SERVER_STARTUP_TIMEOUT);
    if !ok {
        let _ = child.kill();
        let _ = child.wait();
        panic!("server did not start within timeout");
    }

    let url = format!("http://127.0.0.1:{}/pricing", port);
    let resp = reqwest::blocking::get(&url).expect("GET request");
    let status = resp.status();
    let body_text = resp.text().expect("response body");
    let _ = child.kill();
    let _ = child.wait();

    assert!(
        status.is_success(),
        "GET /pricing should return 2xx, got {status}: {body_text}"
    );
    let body: serde_json::Value = serde_json::from_str(&body_text)
        .unwrap_or_else(|e| panic!("invalid JSON: {e}; {body_text}"));

    let versions = body["versions"]
        .as_array()
        .unwrap_or_else(|| panic!("'versions' must be an array: {body}"));
    assert_eq!(
        versions.len(),
        2,
        "two temporal versions loaded, got: {body}"
    );

    let earlier = &versions[0];
    assert_eq!(
        json_date_ymd(&earlier["effective_from"]),
        Some((2025, 1, 1)),
        "earlier version effective_from: {earlier}"
    );
    assert_eq!(
        json_date_ymd(&earlier["effective_to"]),
        Some((2026, 1, 1)),
        "earlier version effective_to equals next version's effective_from: {earlier}"
    );

    let latest = &versions[1];
    assert_eq!(
        json_date_ymd(&latest["effective_from"]),
        Some((2026, 1, 1)),
        "latest version effective_from: {latest}"
    );
    assert!(
        latest["effective_to"].is_null(),
        "latest version effective_to must be null (no successor): {latest}"
    );
}

/// POST evaluate must report the resolved spec version's declared temporal window,
/// both in the JSON body (`spec_effective_from`/`spec_effective_to`) and as the
/// Memento `Memento-Datetime` response header (RFC 7089), scoped to whichever
/// version `?effective=` (or now) resolved to — not the request's own instant.
#[test]
fn post_evaluate_reports_resolved_spec_version_window_in_body_and_memento_header() {
    let temp_dir = tempfile::tempdir().unwrap();
    std::fs::write(
        temp_dir.path().join("temporal.lemma"),
        r#"spec pricing 2025-01-01
data base: 10
rule total: base

spec pricing 2026-01-01
data base: 99
rule total: base
"#,
    )
    .unwrap();

    let port = SERVER_TEST_PORT + 12;
    let bin = env!("CARGO_BIN_EXE_lemma");
    let mut child = std::process::Command::new(bin)
        .arg("server")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("--port")
        .arg(port.to_string())
        .spawn()
        .unwrap();

    let ok = wait_for_port(port, SERVER_STARTUP_TIMEOUT);
    if !ok {
        let _ = child.kill();
        let _ = child.wait();
        panic!("server did not start within timeout");
    }

    let client = reqwest::blocking::Client::new();
    let url = format!("http://127.0.0.1:{}/pricing", port);
    let resp = client
        .post(&url)
        .header("Accept-Datetime", "2025-06-01")
        .send()
        .expect("POST request");
    let status = resp.status();
    let memento_header = resp
        .headers()
        .get("memento-datetime")
        .and_then(|v| v.to_str().ok())
        .map(str::to_string);
    let body_text = resp.text().expect("response body");
    let _ = child.kill();
    let _ = child.wait();

    assert!(
        status.is_success(),
        "POST /pricing should return 2xx, got {status}: {body_text}"
    );
    let body: serde_json::Value = serde_json::from_str(&body_text)
        .unwrap_or_else(|e| panic!("invalid JSON: {e}; {body_text}"));

    assert_eq!(
        json_date_ymd(&body["spec_effective_from"]),
        Some((2025, 1, 1)),
        "resolved spec version's effective_from (2025 slice, not the 2026 successor): {body}"
    );
    assert_eq!(
        json_date_ymd(&body["spec_effective_to"]),
        Some((2026, 1, 1)),
        "resolved spec version's effective_to equals the next version's effective_from: {body}"
    );

    let memento = memento_header.expect("Memento-Datetime header must be present");
    assert!(
        memento.starts_with("2025-01-01"),
        "Memento-Datetime must reflect the resolved version's effective_from, got '{memento}'"
    );
}

#[test]
fn post_evaluate_without_explanations_exposes_rule_missing_data() {
    let temp_dir = tempfile::tempdir().unwrap();
    std::fs::write(
        temp_dir.path().join("suggest.lemma"),
        r#"spec suggest_demo
data n: number -> suggest 42
rule r: n
"#,
    )
    .unwrap();

    let port = SERVER_TEST_PORT + 10;
    let bin = env!("CARGO_BIN_EXE_lemma");
    let mut child = std::process::Command::new(bin)
        .arg("server")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("--port")
        .arg(port.to_string())
        .spawn()
        .unwrap();

    let ok = wait_for_port(port, SERVER_STARTUP_TIMEOUT);
    if !ok {
        let _ = child.kill();
        let _ = child.wait();
        panic!("server did not start within timeout");
    }

    let client = reqwest::blocking::Client::new();
    let url = format!("http://127.0.0.1:{}/suggest_demo", port);
    let resp = client
        .post(&url)
        .header("Content-Type", "application/json")
        .body("{}")
        .send()
        .expect("POST request");
    let status = resp.status();
    let body: serde_json::Value =
        serde_json::from_str(&resp.text().expect("response body")).expect("JSON body");
    let _ = child.kill();
    let _ = child.wait();

    assert!(
        status.is_success(),
        "POST without explanations should return 2xx, got {status}: {body}"
    );
    assert!(
        body.get("data").is_none(),
        "evaluate body must not include top-level data: {body}"
    );
    let rule = body["results"]["r"].as_object().expect("rule r in results");
    assert!(
        rule.get("explanation").is_none(),
        "explanation must stay omitted without x-explanations: {rule:?}"
    );
    let missing = rule["missing_data"]
        .as_array()
        .expect("results.r.missing_data");
    assert!(
        missing.iter().any(|v| v.as_str() == Some("n")),
        "unbound n must appear in missing_data: {missing:?}"
    );
}

#[test]
fn post_evaluate_incomplete_rule_exposes_results_missing_data() {
    let temp_dir = tempfile::tempdir().unwrap();
    std::fs::write(
        temp_dir.path().join("incomplete.lemma"),
        r#"spec incomplete
data a: number
data b: number
rule main: a + b
"#,
    )
    .unwrap();

    let port = SERVER_TEST_PORT + 11;
    let bin = env!("CARGO_BIN_EXE_lemma");
    let mut child = std::process::Command::new(bin)
        .arg("server")
        .arg("--prefix")
        .arg(temp_dir.path())
        .arg("--port")
        .arg(port.to_string())
        .spawn()
        .unwrap();

    if !wait_for_port(port, SERVER_STARTUP_TIMEOUT) {
        let _ = child.kill();
        let _ = child.wait();
        panic!("server did not start within timeout");
    }

    let client = reqwest::blocking::Client::new();
    let url = format!("http://127.0.0.1:{}/incomplete", port);
    let resp = client
        .post(&url)
        .header("Content-Type", "application/json")
        .body("{}")
        .send()
        .expect("POST request");
    let status = resp.status();
    let body: serde_json::Value =
        serde_json::from_str(&resp.text().expect("response body")).expect("JSON body");
    let _ = child.kill();
    let _ = child.wait();

    assert!(
        status.is_success(),
        "POST should return 2xx, got {status}: {body}"
    );
    let missing = body["results"]["main"]["missing_data"]
        .as_array()
        .expect("results.main.missing_data must be an array");
    let keys: Vec<&str> = missing.iter().filter_map(|v| v.as_str()).collect();
    assert_eq!(
        keys,
        ["a", "b"],
        "smoke: missing_data must list unbound inputs: {body}"
    );
}