lemma 0.8.18

A language that means business.
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
pub mod http {
    use crate::formatter::Formatter;
    use axum::{
        body::Bytes,
        extract::{Path, Query, State},
        http::{header::CONTENT_TYPE, HeaderMap, HeaderValue, StatusCode},
        response::{Html, IntoResponse, Json},
        routing::get,
        Router,
    };
    use lemma::collect_lemma_sources as engine_collect_sources;
    use lemma::DateTimeValue;
    use lemma::Engine;
    use lemma_cli::deps::{dependency_identifier_from_dependency_path, lemma_deps_dir};
    use serde::Deserialize;

    use std::net::SocketAddr;
    use std::path::PathBuf;
    use std::sync::Arc;
    use tokio::sync::RwLock;
    use tower_http::cors::CorsLayer;
    use tracing::{error, info, warn};

    type SharedEngine = Arc<RwLock<Engine>>;

    fn parse_spec_path(path: &str) -> String {
        path.trim_matches('/').to_string()
    }

    /// Read Accept-Datetime (RFC 7089) from headers; fallback to now.
    fn accept_datetime_from_headers(
        headers: &HeaderMap,
    ) -> Result<DateTimeValue, (StatusCode, Json<ErrorResponse>)> {
        let raw = headers
            .get("Accept-Datetime")
            .and_then(|v| v.to_str().ok())
            .map(|s| s.trim());
        resolve_effective(raw)
    }

    #[derive(Deserialize, Default)]
    struct EffectiveQuery {
        effective: Option<String>,
    }

    #[derive(Deserialize, Default)]
    struct SpecQuery {
        rules: Option<String>,
    }

    fn resolve_effective(
        raw: Option<&str>,
    ) -> Result<DateTimeValue, (StatusCode, Json<ErrorResponse>)> {
        lemma::Engine::resolve_effective(raw).map_err(|e| {
            (
                StatusCode::BAD_REQUEST,
                Json(ErrorResponse {
                    error: e.message().to_string(),
                }),
            )
        })
    }

    #[derive(Clone)]
    struct AppState {
        engine: SharedEngine,
        explanations_enabled: bool,
    }

    #[derive(Debug, serde::Serialize)]
    struct ErrorResponse {
        error: String,
    }

    #[derive(serde::Serialize)]
    struct GetSpecResponse {
        spec_set_id: String,
        effective_from: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        data: Option<serde_json::Value>,
        #[serde(skip_serializing_if = "Option::is_none")]
        rules: Option<serde_json::Value>,
        #[serde(skip_serializing_if = "Option::is_none")]
        meta: Option<serde_json::Value>,
        versions: Vec<VersionEntry>,
    }

    /// Temporal version entry for a single spec row.
    ///
    /// Ranges are half-open: `[effective_from, effective_to)`. `effective_from = None`
    /// means the range is unbounded at the start (no earlier version exists).
    /// `effective_to = None` means the range is unbounded at the end (no later
    /// version exists; this row is still the latest).
    #[derive(serde::Serialize)]
    struct VersionEntry {
        effective_from: Option<String>,
        effective_to: Option<String>,
    }

    /// Build Memento-Datetime, Vary for the resolved spec.
    fn spec_response_headers(
        effective_from: Option<&DateTimeValue>,
    ) -> Vec<(axum::http::header::HeaderName, HeaderValue)> {
        let mut h = Vec::new();
        if let Some(af) = effective_from {
            if let Ok(v) = HeaderValue::from_str(&af.to_string()) {
                h.push((
                    axum::http::header::HeaderName::from_static("memento-datetime"),
                    v,
                ));
            }
        }
        h.push((
            axum::http::header::VARY,
            HeaderValue::from_static("Accept-Datetime"),
        ));
        h
    }

    /// Start the Lemma HTTP server.
    ///
    ///         The server auto-generates typed REST endpoints for each loaded spec:
    /// - `GET /{spec}/{rules?}` — evaluate rules (all if rules omitted), data as query params
    /// - `POST /{spec}/{rules?}` — evaluate rules (all if rules omitted), data as JSON or form body
    ///
    /// Meta routes:
    /// - `GET /` — list all specs
    /// - `GET /health` — health check
    /// - `GET /openapi.json` — OpenAPI 3.1 specification
    /// - `GET /docs` — Scalar interactive documentation
    pub async fn start_server(
        engine: Engine,
        host: &str,
        port: u16,
        watch: bool,
        explanations: bool,
        workdir: PathBuf,
    ) -> anyhow::Result<()> {
        tracing_subscriber::fmt()
            .with_env_filter(
                tracing_subscriber::EnvFilter::try_from_default_env()
                    .unwrap_or_else(|_| "lemma=info,tower_http=info".into()),
            )
            .init();

        let shared_engine: SharedEngine = Arc::new(RwLock::new(engine));

        if watch {
            start_file_watcher(shared_engine.clone(), workdir)?;
        }

        let state = AppState {
            engine: shared_engine,
            explanations_enabled: explanations,
        };

        let app = Router::new()
            .route("/", get(list_specs))
            .route("/health", get(health_check))
            .route("/openapi.json", get(openapi_spec))
            .route("/docs", get(scalar_docs))
            .route("/scalar.js", get(scalar_js))
            .route("/{*path}", get(spec_get_schema).post(spec_post_evaluate))
            .fallback(fallback_404)
            .layer(CorsLayer::permissive())
            .with_state(state);

        let addr: SocketAddr = format!("{host}:{port}").parse()?;
        info!("Lemma server listening on http://{}", addr);
        info!("Interactive docs at http://{}/docs", addr);

        let listener = tokio::net::TcpListener::bind(addr).await?;
        axum::serve(listener, app).await?;

        Ok(())
    }

    // -----------------------------------------------------------------------
    // Meta routes
    // -----------------------------------------------------------------------

    async fn list_specs(
        State(state): State<AppState>,
        Query(q): Query<EffectiveQuery>,
    ) -> Result<impl IntoResponse, (StatusCode, Json<ErrorResponse>)> {
        let now = resolve_effective(q.effective.as_deref())?;
        let engine = state.engine.read().await;

        let specs: Vec<lemma::SpecSchema> = engine
            .get_workspace()
            .specs
            .iter()
            .filter_map(|ss| engine.schema(None, &ss.name, Some(&now)).ok())
            .collect();

        Ok(Json(specs))
    }

    async fn health_check() -> impl IntoResponse {
        Json(serde_json::json!({
            "status": "ok",
            "service": "lemma",
            "version": env!("CARGO_PKG_VERSION")
        }))
    }

    /// Fallback when no route matches — return 404 with JSON body (never empty).
    async fn fallback_404() -> (StatusCode, Json<ErrorResponse>) {
        (
            StatusCode::NOT_FOUND,
            Json(ErrorResponse {
                error: "Not found. Use GET / for spec list, GET /docs for API docs.".to_string(),
            }),
        )
    }

    async fn openapi_spec(
        State(state): State<AppState>,
        Query(q): Query<EffectiveQuery>,
    ) -> Result<impl IntoResponse, (StatusCode, Json<ErrorResponse>)> {
        let effective = resolve_effective(q.effective.as_deref())?;
        let engine = state.engine.read().await;
        let spec = lemma_openapi::generate_openapi_effective(
            &engine,
            state.explanations_enabled,
            &effective,
        );
        Ok(Json(spec))
    }

    async fn scalar_docs(State(state): State<AppState>) -> impl IntoResponse {
        let engine = state.engine.read().await;
        let sources = lemma_openapi::temporal_api_sources(&engine);

        let shared_opts = r#"layout: 'modern',
      theme: 'solarized',
      agent: { disabled: true },
      hideClientButton: true,
      hideTestRequestButton: false,
      showSidebar: true,
      showDeveloperTools: 'never',
      operationTitleSource: 'summary',
      persistAuth: false,
      telemetry: false,
      hideModels: true,
      documentDownloadType: 'both', // Scalar UI option, not Lemma
      hideSearch: false,
      showOperationId: false,
      hideDarkModeToggle: false,
      withDefaultFonts: false,
      defaultOpenAllTags: false,
      expandAllModelSections: true,
      expandAllResponses: true,
      orderSchemaPropertiesBy: 'alpha',
      orderRequiredPropertiesFirst: true,
      customCss: `
        a[href="https://www.scalar.com"] {
          font-size: 0 !important;
        }
        a[href="https://www.scalar.com"]::after {
          content: 'Powered by Lemma';
          font-size: var(--scalar-mini, 10px);
        }
      `"#;

        let config_js = if sources.len() == 1 {
            format!("{{ url: '{}', {} }}", sources[0].url, shared_opts)
        } else {
            let sources_js: Vec<String> = sources
                .iter()
                .map(|s| {
                    format!(
                        "{{ title: '{}', slug: '{}', url: '{}' }}",
                        s.title, s.slug, s.url
                    )
                })
                .collect();
            format!(
                "{{ sources: [{}], {} }}",
                sources_js.join(", "),
                shared_opts
            )
        };

        let html = format!(
            r#"<!doctype html>
<html>
<head>
  <title>Lemma API</title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
  <div id="app"></div>
  <script src="/scalar.js"></script>
  <script>
    Scalar.createApiReference('#app', {config_js})
  </script>
</body>
</html>"#
        );

        Html(html)
    }

    /// Serve the vendored Scalar API reference JavaScript bundle.
    /// Embedded at compile time so the server has zero external dependencies.
    async fn scalar_js() -> impl IntoResponse {
        static SCALAR_JS: &str = include_str!("../vendor/scalar-api-reference.js");

        (
            [(
                axum::http::header::CONTENT_TYPE,
                "application/javascript; charset=utf-8",
            )],
            SCALAR_JS,
        )
    }

    // -----------------------------------------------------------------------
    // Doc path (wildcard): GET = schema with versions, POST = evaluate
    // -----------------------------------------------------------------------

    /// `GET /{*path}` — schema of resolved version; path = specset id. `Accept-Datetime` for temporal, `?rules=` to scope.
    async fn spec_get_schema(
        State(state): State<AppState>,
        Path(path): Path<String>,
        Query(q): Query<SpecQuery>,
        headers: HeaderMap,
    ) -> Result<impl IntoResponse, (StatusCode, Json<ErrorResponse>)> {
        let spec_set_id = parse_spec_path(&path);
        let effective = accept_datetime_from_headers(&headers)?;
        let engine = state.engine.read().await;

        let spec_name = lemma::parse_spec_set_id(&spec_set_id).map_err(|e| {
            (
                StatusCode::BAD_REQUEST,
                Json(ErrorResponse {
                    error: e.to_string(),
                }),
            )
        })?;

        let schema = engine
            .schema(None, &spec_name, Some(&effective))
            .map_err(|e| {
                (
                    lemma_error_to_status(&e),
                    Json(ErrorResponse {
                        error: e.to_string(),
                    }),
                )
            })?;

        let rule_names = q.rules.as_deref().map(parse_rule_names).unwrap_or_default();
        let schema = if rule_names.is_empty() {
            schema
        } else {
            let plan = engine
                .get_plan(None, &spec_name, Some(&effective))
                .map_err(|e| {
                    (
                        lemma_error_to_status(&e),
                        Json(ErrorResponse {
                            error: e.to_string(),
                        }),
                    )
                })?;
            plan.schema_for_rules(&rule_names, &lemma::DataOverlay::default())
                .map_err(|err| {
                    (
                        lemma_error_to_status(&err),
                        Json(ErrorResponse {
                            error: err.to_string(),
                        }),
                    )
                })?
        };

        let spec_arc = engine.get_spec(&spec_name, Some(&effective)).map_err(|e| {
            (
                lemma_error_to_status(&e),
                Json(ErrorResponse {
                    error: e.to_string(),
                }),
            )
        })?;

        let versions: Vec<VersionEntry> = engine
            .get_workspace()
            .specs
            .iter()
            .filter(|ss| ss.name == spec_arc.name)
            .flat_map(|ss| ss.iter_with_ranges())
            .map(|(_, effective_from, effective_to)| VersionEntry {
                effective_from: effective_from.as_ref().map(|d| d.to_string()),
                effective_to: effective_to.as_ref().map(|d| d.to_string()),
            })
            .collect();

        let effective_from_str = spec_arc.effective_from().map(|d| d.to_string());

        let body = GetSpecResponse {
            spec_set_id,
            effective_from: effective_from_str,
            data: Some(
                serde_json::to_value(&schema.data).expect("BUG: failed to serialize schema data"),
            ),
            rules: Some(
                serde_json::to_value(&schema.rules).expect("BUG: failed to serialize schema rules"),
            ),
            meta: Some(
                serde_json::to_value(&schema.meta).expect("BUG: failed to serialize schema meta"),
            ),
            versions,
        };

        let mut response = Json(body).into_response();
        let headers_mut = response.headers_mut();
        for (k, v) in spec_response_headers(spec_arc.effective_from()) {
            headers_mut.insert(k, v);
        }
        Ok(response)
    }

    fn parse_post_evaluate_body(
        headers: &HeaderMap,
        body: &[u8],
    ) -> Result<
        std::collections::HashMap<String, lemma::DataValueInput>,
        (StatusCode, Json<ErrorResponse>),
    > {
        if body.is_empty() {
            return Ok(std::collections::HashMap::new());
        }

        let content_type = headers
            .get(CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .map(|s| s.split(';').next().unwrap_or(s).trim().to_ascii_lowercase())
            .unwrap_or_default();

        let data_values = match content_type.as_str() {
            "application/json" => {
                let map: std::collections::HashMap<String, serde_json::Value> =
                    serde_json::from_slice(body).map_err(|e| {
                        (
                            StatusCode::BAD_REQUEST,
                            Json(ErrorResponse {
                                error: format!("invalid JSON body: {e}"),
                            }),
                        )
                    })?;
                map.into_iter()
                    .filter(|(_, v)| !v.is_null())
                    .map(|(k, v)| {
                        crate::data_json::json_value_to_data_input(v).map(|input| (k, input))
                    })
                    .collect::<Result<_, _>>()
                    .map_err(|e| (StatusCode::BAD_REQUEST, Json(ErrorResponse { error: e })))?
            }
            "application/x-www-form-urlencoded" => {
                crate::data_json::form_urlencoded_to_data_values(body)
                    .map_err(|e| (StatusCode::BAD_REQUEST, Json(ErrorResponse { error: e })))?
            }
            "" => {
                return Err((
                    StatusCode::UNSUPPORTED_MEDIA_TYPE,
                    Json(ErrorResponse {
                        error: "Expected request with Content-Type: application/json or application/x-www-form-urlencoded".to_string(),
                    }),
                ));
            }
            other => {
                return Err((
                    StatusCode::UNSUPPORTED_MEDIA_TYPE,
                    Json(ErrorResponse {
                        error: format!(
                            "Unsupported Content-Type '{other}'; expected application/json or application/x-www-form-urlencoded"
                        ),
                    }),
                ));
            }
        };

        Ok(data_values)
    }

    /// `POST /{*path}` — evaluate; path = specset id. `Accept-Datetime` for temporal, `?rules=` to limit. Body = JSON or form data.
    async fn spec_post_evaluate(
        State(state): State<AppState>,
        Path(path): Path<String>,
        Query(q): Query<SpecQuery>,
        headers: HeaderMap,
        body: Bytes,
    ) -> Result<impl IntoResponse, (StatusCode, Json<ErrorResponse>)> {
        let spec_set_id = parse_spec_path(&path);
        let effective = accept_datetime_from_headers(&headers)?;
        let engine = state.engine.read().await;

        let spec_name = lemma::parse_spec_set_id(&spec_set_id).map_err(|e| {
            (
                StatusCode::BAD_REQUEST,
                Json(ErrorResponse {
                    error: e.to_string(),
                }),
            )
        })?;

        let data_values = parse_post_evaluate_body(&headers, &body)?;

        let plan = engine
            .get_plan(None, &spec_name, Some(&effective))
            .map_err(|err| {
                (
                    lemma_error_to_status(&err),
                    Json(ErrorResponse {
                        error: err.to_string(),
                    }),
                )
            })?;

        let parsed_rules: Option<Vec<String>> = match q.rules.as_deref() {
            None => None,
            Some(rules_query) => {
                let parsed = parse_rule_names(rules_query);
                if parsed.is_empty() {
                    return Err((
                        StatusCode::BAD_REQUEST,
                        Json(ErrorResponse {
                            error: "at least one rule required".to_string(),
                        }),
                    ));
                }
                Some(parsed)
            }
        };

        let include_explanations = want_explanations(&state, &headers);
        let response = engine
            .run_plan(
                plan,
                Some(&effective),
                data_values,
                include_explanations,
                parsed_rules.as_deref(),
            )
            .map_err(|err| {
                (
                    lemma_error_to_status(&err),
                    Json(ErrorResponse {
                        error: err.to_string(),
                    }),
                )
            })?;

        let spec_arc = engine.get_spec(&spec_name, Some(&effective)).ok();
        let effective_from = spec_arc.as_ref().and_then(|a| a.effective_from());
        let payload = Formatter.response_json_value(&response, include_explanations);
        let mut axum_response = Json(payload).into_response();
        let headers_mut = axum_response.headers_mut();
        for (k, v) in spec_response_headers(effective_from) {
            headers_mut.insert(k, v);
        }
        Ok(axum_response)
    }

    fn want_explanations(state: &AppState, headers: &HeaderMap) -> bool {
        state.explanations_enabled
            && headers
                .get("x-explanations")
                .and_then(|v: &axum::http::HeaderValue| v.to_str().ok())
                .map(|s: &str| !s.trim().is_empty())
                .unwrap_or(false)
    }

    /// Map a `Error` to an HTTP status code.
    ///
    /// SpecNotFound → 404; InvalidRequest → 400.
    fn lemma_error_to_status(err: &lemma::Error) -> StatusCode {
        use lemma::RequestErrorKind;
        match err {
            lemma::Error::Request {
                kind: RequestErrorKind::SpecNotFound,
                ..
            } => StatusCode::NOT_FOUND,
            _ => StatusCode::BAD_REQUEST,
        }
    }

    // -----------------------------------------------------------------------
    // Helpers
    // -----------------------------------------------------------------------

    /// Parse comma-separated rule names from a URL path segment.
    /// Filters out empty strings and the literal `{rules}` placeholder that
    /// Scalar sends when the path parameter is left blank.
    fn parse_rule_names(rules_segment: &str) -> Vec<String> {
        rules_segment
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty() && s != "{rules}")
            .collect()
    }

    // -----------------------------------------------------------------------
    // File watcher (--watch mode)
    // -----------------------------------------------------------------------

    /// Snapshot of the last-modified timestamps for all `.lemma` files in the
    /// workspace. Used to detect whether files have actually changed between
    /// watcher callbacks, avoiding needless reloads from access-only events.
    type ModifiedSnapshot = std::collections::BTreeMap<PathBuf, std::time::SystemTime>;

    /// Walk the workspace and collect `(path, modified)` for every `.lemma` file.
    fn collect_modified_times(workdir: &std::path::Path) -> ModifiedSnapshot {
        use walkdir::WalkDir;

        let mut snapshot = std::collections::BTreeMap::new();
        for entry in WalkDir::new(workdir).into_iter().flatten() {
            if entry.path().extension().and_then(|s| s.to_str()) == Some("lemma") {
                if let Ok(metadata) = entry.path().metadata() {
                    if let Ok(modified) = metadata.modified() {
                        snapshot.insert(entry.path().to_path_buf(), modified);
                    }
                }
            }
        }
        snapshot
    }

    fn start_file_watcher(shared_engine: SharedEngine, workdir: PathBuf) -> anyhow::Result<()> {
        use notify_debouncer_mini::new_debouncer;
        use std::sync::Mutex;
        use std::time::Duration;

        let watch_dir = workdir.clone();

        // Track the last-known modified timestamps so we only reload when
        // file contents have actually changed, not on access-only events.
        let last_snapshot: Arc<Mutex<ModifiedSnapshot>> =
            Arc::new(Mutex::new(collect_modified_times(&workdir)));

        // The debouncer thread runs in the background. We intentionally
        // "forget" the handle so the watcher stays alive for the lifetime
        // of the process. Dropping it would stop watching.
        let mut debouncer = new_debouncer(
            Duration::from_millis(500),
            move |result: Result<Vec<notify_debouncer_mini::DebouncedEvent>, notify::Error>| {
                match result {
                    Ok(events) => {
                        let has_lemma_events = events.iter().any(|event| {
                            event
                                .path
                                .extension()
                                .and_then(|ext| ext.to_str())
                                .map(|ext| ext == "lemma")
                                .unwrap_or(false)
                        });

                        if !has_lemma_events {
                            return;
                        }

                        // Check if any file was actually modified by comparing
                        // the current timestamps to the last known snapshot.
                        let current_snapshot = collect_modified_times(&workdir);

                        let files_changed = {
                            let previous = match last_snapshot.lock() {
                                Ok(guard) => guard,
                                Err(poisoned) => poisoned.into_inner(),
                            };
                            current_snapshot != *previous
                        };

                        if !files_changed {
                            return;
                        }

                        // Store the new snapshot before starting the reload so
                        // that subsequent callbacks see the up-to-date times.
                        {
                            let mut previous = match last_snapshot.lock() {
                                Ok(guard) => guard,
                                Err(poisoned) => poisoned.into_inner(),
                            };
                            *previous = current_snapshot;
                        }

                        info!("Detected .lemma file changes, reloading...");
                        let engine_clone = shared_engine.clone();
                        let workdir_clone = workdir.clone();

                        // Spawn a dedicated OS thread for reloading. The notify
                        // callback is synchronous, so we create a fresh tokio
                        // runtime on a new thread to run the async reload.
                        std::thread::spawn(move || {
                            let runtime = match tokio::runtime::Runtime::new() {
                                Ok(rt) => rt,
                                Err(err) => {
                                    error!("Failed to create tokio runtime for reload: {}", err);
                                    return;
                                }
                            };

                            runtime.block_on(async {
                                match reload_engine(&workdir_clone).await {
                                    Ok(new_engine) => {
                                        let spec_count = new_engine.get_workspace().specs.len();
                                        let mut engine = engine_clone.write().await;
                                        *engine = new_engine;
                                        info!("Reloaded engine with {} spec(s)", spec_count);
                                    }
                                    Err(err) => {
                                        warn!("Reload failed (keeping previous state): {}", err);
                                    }
                                }
                            });
                        });
                    }
                    Err(err) => {
                        error!("File watcher error: {}", err);
                    }
                }
            },
        )?;

        debouncer
            .watcher()
            .watch(&watch_dir, notify::RecursiveMode::Recursive)?;

        info!("Watching {:?} for .lemma file changes", watch_dir);

        // Leak the debouncer so the watcher thread stays alive.
        // This is intentional: the watcher should run for the lifetime of the process.
        std::mem::forget(debouncer);

        Ok(())
    }

    /// Create a fresh engine by loading all .lemma files from the workspace
    /// directory (including `lemma_deps/` for cached registry dependencies).
    /// `lemma_deps/` files are loaded as dependencies with IDs derived from their path.
    async fn reload_engine(workdir: &std::path::Path) -> anyhow::Result<Engine> {
        use walkdir::WalkDir;

        let mut engine = Engine::new();
        let deps_dir = lemma_deps_dir(workdir);
        let mut workspace_paths: Vec<std::path::PathBuf> = Vec::new();
        let mut deps_paths: Vec<std::path::PathBuf> = Vec::new();
        for entry in WalkDir::new(workdir) {
            let entry = entry?;
            if entry.path().extension().and_then(|s| s.to_str()) != Some("lemma") {
                continue;
            }
            if entry.path().starts_with(&deps_dir) {
                deps_paths.push(entry.path().to_path_buf());
            } else {
                workspace_paths.push(entry.path().to_path_buf());
            }
        }

        for dep_path in &deps_paths {
            let dependency_id = dependency_identifier_from_dependency_path(workdir, dep_path);
            let sources = match engine_collect_sources(std::slice::from_ref(dep_path)) {
                Ok(s) => s,
                Err(e) => {
                    for err in e.iter() {
                        tracing::error!(
                            "{}",
                            crate::error_formatter::format_error(err, &e.sources)
                        );
                    }
                    anyhow::bail!("Workspace load failed ({} error(s))", e.errors.len());
                }
            };
            if let Err(load_err) = engine.load_batch(sources, Some(&dependency_id)) {
                for err in load_err.iter() {
                    tracing::error!(
                        "{}",
                        crate::error_formatter::format_error(err, &load_err.sources)
                    );
                }
                anyhow::bail!("Workspace load failed ({} error(s))", load_err.errors.len());
            }
        }
        let sources = match engine_collect_sources(&workspace_paths) {
            Ok(s) => s,
            Err(e) => {
                for err in e.iter() {
                    tracing::error!("{}", crate::error_formatter::format_error(err, &e.sources));
                }
                anyhow::bail!("Workspace load failed ({} error(s))", e.errors.len());
            }
        };
        if let Err(load_err) = engine.load_batch(sources, None) {
            for err in load_err.iter() {
                tracing::error!(
                    "{}",
                    crate::error_formatter::format_error(err, &load_err.sources)
                );
            }
            anyhow::bail!("Workspace load failed ({} error(s))", load_err.errors.len());
        }
        Ok(engine)
    }
}