Skip to main content

lemma_cli/
workspace.rs

1//! Workspace disk policy: discover, load, and watch `.lemma` files.
2//!
3//! Discovery respects project `.gitignore` via the `ignore` crate, and always
4//! includes `<workdir>/lemma_deps/**/*.lemma` even when that directory is gitignored.
5
6use crate::deps::{dependency_identifier_from_dependency_path, lemma_deps_dir};
7use lemma::Engine;
8use std::collections::hash_map::DefaultHasher;
9use std::collections::BTreeMap;
10use std::fs;
11use std::hash::{Hash, Hasher};
12use std::path::{Path, PathBuf};
13use std::sync::mpsc::Sender;
14use std::sync::{Arc, Mutex};
15use std::time::Duration;
16use walkdir::WalkDir;
17
18/// Paths discovered under a workspace root, partitioned by provenance.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct DiscoveredPaths {
21    /// Workspace `.lemma` files (not under `lemma_deps/`).
22    pub workspace_paths: Vec<PathBuf>,
23    /// Dependency bundles under `lemma_deps/`.
24    pub dependency_paths: Vec<PathBuf>,
25}
26
27impl DiscoveredPaths {
28    /// Every discovered path (dependencies first, then workspace), for snapshots.
29    pub fn all_paths(&self) -> impl Iterator<Item = &PathBuf> {
30        self.dependency_paths
31            .iter()
32            .chain(self.workspace_paths.iter())
33    }
34}
35
36/// Failure discovering or reading workspace sources from disk.
37#[derive(Debug)]
38pub enum WorkspaceDiskError {
39    Io(std::io::Error),
40    Ignore(ignore::Error),
41    Walkdir(walkdir::Error),
42    EngineLoad(lemma::Errors),
43}
44
45impl std::fmt::Display for WorkspaceDiskError {
46    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        match self {
48            Self::Io(error) => write!(formatter, "{error}"),
49            Self::Ignore(error) => write!(formatter, "{error}"),
50            Self::Walkdir(error) => write!(formatter, "{error}"),
51            Self::EngineLoad(errors) => {
52                write!(
53                    formatter,
54                    "Workspace load failed ({} error(s))",
55                    errors.errors.len()
56                )
57            }
58        }
59    }
60}
61
62impl std::error::Error for WorkspaceDiskError {
63    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
64        match self {
65            Self::Io(error) => Some(error),
66            Self::Ignore(error) => Some(error),
67            Self::Walkdir(error) => Some(error),
68            Self::EngineLoad(_) => None,
69        }
70    }
71}
72
73impl From<std::io::Error> for WorkspaceDiskError {
74    fn from(error: std::io::Error) -> Self {
75        Self::Io(error)
76    }
77}
78
79impl From<ignore::Error> for WorkspaceDiskError {
80    fn from(error: ignore::Error) -> Self {
81        Self::Ignore(error)
82    }
83}
84
85impl From<walkdir::Error> for WorkspaceDiskError {
86    fn from(error: walkdir::Error) -> Self {
87        Self::Walkdir(error)
88    }
89}
90
91/// Discover `.lemma` paths under `workdir` (or a single `.lemma` file).
92///
93/// Directory roots: gitignore-aware walk excluding `lemma_deps/`, plus an
94/// unconditional walk of `lemma_deps/` for dependency bundles.
95pub fn discover_lemma_paths(workdir: &Path) -> Result<DiscoveredPaths, WorkspaceDiskError> {
96    if workdir.is_file() {
97        return Ok(DiscoveredPaths {
98            workspace_paths: vec![workdir.to_path_buf()],
99            dependency_paths: Vec::new(),
100        });
101    }
102
103    let deps_dir = lemma_deps_dir(workdir);
104    let mut workspace_paths = Vec::new();
105    let mut dependency_paths = Vec::new();
106
107    for entry in ignore::WalkBuilder::new(workdir)
108        .hidden(true)
109        .git_ignore(true)
110        .git_global(false)
111        .git_exclude(false)
112        .require_git(false)
113        .build()
114    {
115        let entry = entry?;
116        let path = entry.path();
117        if path.starts_with(&deps_dir) {
118            continue;
119        }
120        if path.extension().and_then(|ext| ext.to_str()) != Some("lemma") {
121            continue;
122        }
123        if path.is_file() {
124            workspace_paths.push(path.to_path_buf());
125        }
126    }
127
128    if deps_dir.is_dir() {
129        for entry in WalkDir::new(&deps_dir) {
130            let entry = entry?;
131            let path = entry.path();
132            if path.extension().and_then(|ext| ext.to_str()) != Some("lemma") {
133                continue;
134            }
135            if path.is_file() {
136                dependency_paths.push(path.to_path_buf());
137            }
138        }
139    }
140
141    workspace_paths.sort();
142    dependency_paths.sort();
143
144    Ok(DiscoveredPaths {
145        workspace_paths,
146        dependency_paths,
147    })
148}
149
150/// Engine [`SourceType::Path`] label for a discovered workspace file.
151///
152/// Absolute disk paths are used only for I/O. Engine identity matches MCP/SDK
153/// attributes: path relative to `workdir`, or the file name when `workdir` is
154/// the file itself.
155pub fn workspace_path_label(workdir: &Path, absolute_path: &Path) -> std::sync::Arc<PathBuf> {
156    if workdir.is_file() {
157        assert_eq!(
158            absolute_path, workdir,
159            "BUG: single-file workspace discover must yield the workdir path"
160        );
161        let name = workdir
162            .file_name()
163            .expect("BUG: workspace file path must have a file name");
164        return std::sync::Arc::new(PathBuf::from(name));
165    }
166    let relative = absolute_path.strip_prefix(workdir).unwrap_or_else(|_| {
167        panic!(
168            "BUG: discovered path {} is not under workdir {}",
169            absolute_path.display(),
170            workdir.display()
171        )
172    });
173    std::sync::Arc::new(relative.to_path_buf())
174}
175
176/// Load discovered sources into `engine` (same provenance rules as the CLI always used).
177pub fn load_workspace(engine: &mut Engine, workdir: &Path) -> Result<(), WorkspaceDiskError> {
178    load_workspace_excluding(engine, workdir, &[])
179}
180
181/// Like [`load_workspace`], but skips paths in `exclude` (compared as [`Path`]).
182///
183/// Used by install plan probe so `destination_absolute` and pending force
184/// `conflict_paths` are not loaded; the candidate is loaded separately.
185pub fn load_workspace_excluding(
186    engine: &mut Engine,
187    workdir: &Path,
188    exclude: &[&Path],
189) -> Result<(), WorkspaceDiskError> {
190    let discovered = discover_lemma_paths(workdir)?;
191    let mut sources = Vec::with_capacity(
192        discovered
193            .dependency_paths
194            .len()
195            .saturating_add(discovered.workspace_paths.len()),
196    );
197
198    for dep_path in &discovered.dependency_paths {
199        if exclude.contains(&dep_path.as_path()) {
200            continue;
201        }
202        let dependency_id = dependency_identifier_from_dependency_path(workdir, dep_path);
203        let content = fs::read_to_string(dep_path)?;
204        sources.push((
205            lemma::SourceType::Dependency(dependency_id.to_string()),
206            content,
207        ));
208    }
209    for path in &discovered.workspace_paths {
210        if exclude.contains(&path.as_path()) {
211            continue;
212        }
213        let content = fs::read_to_string(path)?;
214        sources.push((
215            lemma::SourceType::Path(workspace_path_label(workdir, path)),
216            content,
217        ));
218    }
219
220    if sources.is_empty() {
221        return Ok(());
222    }
223
224    match engine.load(sources) {
225        Ok(()) => Ok(()),
226        Err(errors) => Err(WorkspaceDiskError::EngineLoad(errors)),
227    }
228}
229
230/// Refresh an existing engine from disk.
231///
232/// Discovers current `.lemma` paths and batch-[`Engine::load`]s them into a
233/// scratch engine (order-independent), then swaps into `engine` only on success.
234/// Failure leaves `engine` untouched. Callers that previously relied on
235/// per-file `update` for scoped replanning still get a correct workspace; the
236/// HTTP `--watch` path prioritizes last-good over incremental mutation.
237pub fn refresh_workspace_via_update(
238    engine: &mut Engine,
239    workdir: &Path,
240) -> Result<(), WorkspaceDiskError> {
241    let discovered = discover_lemma_paths(workdir)?;
242    let mut sources: Vec<(lemma::SourceType, String)> = Vec::new();
243
244    for dep_path in &discovered.dependency_paths {
245        let dependency_id = dependency_identifier_from_dependency_path(workdir, dep_path);
246        let source_type = lemma::SourceType::Dependency(dependency_id.to_string());
247        let content = fs::read_to_string(dep_path)?;
248        sources.push((source_type, content));
249    }
250    for path in &discovered.workspace_paths {
251        let source_type = lemma::SourceType::Path(workspace_path_label(workdir, path));
252        let content = fs::read_to_string(path)?;
253        sources.push((source_type, content));
254    }
255
256    let mut scratch = Engine::new();
257    scratch
258        .load(sources)
259        .map_err(WorkspaceDiskError::EngineLoad)?;
260    *engine = scratch;
261    Ok(())
262}
263
264/// Discover-set fingerprint: path → content hash.
265///
266/// Mtime alone is not enough: on filesystems that keep the same `mtime` across
267/// rapid same-length rewrites, a real content change would look identical and the
268/// watch would never deliver `Ok(())`.
269type DiscoverSnapshot = BTreeMap<PathBuf, u64>;
270
271fn content_fingerprint(path: &Path) -> Result<u64, WorkspaceDiskError> {
272    let bytes = fs::read(path)?;
273    let mut hasher = DefaultHasher::new();
274    bytes.hash(&mut hasher);
275    Ok(hasher.finish())
276}
277
278fn collect_discover_snapshot(workdir: &Path) -> Result<DiscoverSnapshot, WorkspaceDiskError> {
279    let discovered = discover_lemma_paths(workdir)?;
280    let mut snapshot = BTreeMap::new();
281    for path in discovered.all_paths() {
282        snapshot.insert(path.clone(), content_fingerprint(path)?);
283    }
284    Ok(snapshot)
285}
286
287/// Watch target: path plus whether the watch is recursive.
288type WatchTarget = (PathBuf, bool);
289
290fn push_ancestor_dirs(targets: &mut Vec<WatchTarget>, workdir: &Path, file_path: &Path) {
291    let mut current = match file_path.parent() {
292        Some(parent) => parent,
293        None => return,
294    };
295    loop {
296        targets.push((current.to_path_buf(), false));
297        if current == workdir {
298            break;
299        }
300        match current.parent() {
301            Some(parent) if parent != current => current = parent,
302            _ => break,
303        }
304    }
305}
306
307fn desired_watch_targets(workdir: &Path) -> Result<Vec<WatchTarget>, WorkspaceDiskError> {
308    let mut targets = Vec::new();
309
310    // Non-recursive watch on the workspace root sees `lemma_deps/` appear without
311    // descending into `target/` or other large trees.
312    if workdir.is_dir() {
313        targets.push((workdir.to_path_buf(), false));
314    }
315
316    let deps_dir = lemma_deps_dir(workdir);
317    if deps_dir.is_dir() {
318        targets.push((deps_dir.clone(), true));
319    }
320
321    let discovered = discover_lemma_paths(workdir)?;
322    for path in &discovered.workspace_paths {
323        push_ancestor_dirs(&mut targets, workdir, path);
324    }
325
326    // Dynamic expand: non-recursive watch on every non-ignored directory under
327    // workdir (except lemma_deps, covered recursively). New child dirs become
328    // visible on the next plant after the parent wakes.
329    if workdir.is_dir() {
330        for entry in ignore::WalkBuilder::new(workdir)
331            .hidden(true)
332            .git_ignore(true)
333            .git_global(false)
334            .git_exclude(false)
335            .require_git(false)
336            .build()
337        {
338            let entry = entry?;
339            let path = entry.path();
340            if path.starts_with(&deps_dir) {
341                continue;
342            }
343            if path.is_dir() {
344                targets.push((path.to_path_buf(), false));
345            }
346        }
347    }
348
349    targets.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| left.1.cmp(&right.1)));
350    targets.dedup();
351    Ok(targets)
352}
353
354fn plant_watches(
355    watcher: &mut dyn notify::Watcher,
356    workdir: &Path,
357    currently_watched: &Mutex<std::collections::BTreeSet<WatchTarget>>,
358) -> Result<(), WorkspaceDiskError> {
359    let desired = desired_watch_targets(workdir)?;
360    let desired_set: std::collections::BTreeSet<WatchTarget> = desired.into_iter().collect();
361
362    let mut current = match currently_watched.lock() {
363        Ok(guard) => guard,
364        Err(poisoned) => poisoned.into_inner(),
365    };
366
367    for target in current.difference(&desired_set) {
368        watcher
369            .unwatch(&target.0)
370            .map_err(|error| WorkspaceDiskError::Io(std::io::Error::other(error)))?;
371    }
372    for target in desired_set.difference(&current) {
373        let mode = if target.1 {
374            notify::RecursiveMode::Recursive
375        } else {
376            notify::RecursiveMode::NonRecursive
377        };
378        watcher
379            .watch(&target.0, mode)
380            .map_err(|error| WorkspaceDiskError::Io(std::io::Error::other(error)))?;
381    }
382    *current = desired_set;
383    Ok(())
384}
385
386/// Keeps the filesystem watcher alive until dropped.
387///
388/// The notify callback holds a clone of the same `Arc` as this guard, and the
389/// debouncer owns the callback. Drop takes the debouncer out of the mutex so
390/// that cycle breaks and the notify thread stops.
391pub struct WatchGuard {
392    debouncer: Arc<Mutex<Option<notify_debouncer_mini::Debouncer<notify::RecommendedWatcher>>>>,
393}
394
395impl Drop for WatchGuard {
396    fn drop(&mut self) {
397        let mut slot = match self.debouncer.lock() {
398            Ok(guard) => guard,
399            Err(poisoned) => poisoned.into_inner(),
400        };
401        *slot = None;
402    }
403}
404
405/// Sends one watch event. A dropped receiver means the watch is being torn down.
406fn deliver<T>(sink: &Sender<T>, event: T) {
407    if sink.send(event).is_err() {
408        // receiver gone: the owning guard is being dropped
409    }
410}
411
412/// Watch discovered `.lemma` paths under `workdir` (not the whole tree recursively).
413///
414/// Plants non-recursive watches on `workdir`, on every non-ignored directory under
415/// it, and on ancestors of discovered workspace `.lemma` files; plus `lemma_deps/`
416/// recursively when that directory exists.
417///
418/// Every event is sent to `on_change` from the notify debouncer thread: `Ok(())` when
419/// the discover snapshot changed; `Err` when discover/watch maintenance failed. The
420/// receiver owns any async or blocking work.
421pub fn watch_lemma_workspace(
422    workdir: PathBuf,
423    on_change: Sender<Result<(), WorkspaceDiskError>>,
424) -> Result<WatchGuard, WorkspaceDiskError> {
425    let initial_snapshot = collect_discover_snapshot(&workdir)?;
426    let last_snapshot: Arc<Mutex<DiscoverSnapshot>> = Arc::new(Mutex::new(initial_snapshot));
427    let currently_watched: Arc<Mutex<std::collections::BTreeSet<WatchTarget>>> =
428        Arc::new(Mutex::new(std::collections::BTreeSet::new()));
429    let debouncer_slot: Arc<
430        Mutex<Option<notify_debouncer_mini::Debouncer<notify::RecommendedWatcher>>>,
431    > = Arc::new(Mutex::new(None));
432
433    let workdir_for_callback = workdir.clone();
434    let snapshot_for_callback = Arc::clone(&last_snapshot);
435    let watched_for_callback = Arc::clone(&currently_watched);
436    let slot_for_callback = Arc::clone(&debouncer_slot);
437    let on_change_for_callback = on_change;
438
439    let mut debouncer = notify_debouncer_mini::new_debouncer(
440        Duration::from_millis(500),
441        move |result: Result<Vec<notify_debouncer_mini::DebouncedEvent>, notify::Error>| {
442            if let Err(error) = result {
443                deliver(
444                    &on_change_for_callback,
445                    Err(WorkspaceDiskError::Io(std::io::Error::other(error))),
446                );
447                return;
448            }
449
450            let current_snapshot = match collect_discover_snapshot(&workdir_for_callback) {
451                Ok(snapshot) => snapshot,
452                Err(error) => {
453                    deliver(&on_change_for_callback, Err(error));
454                    return;
455                }
456            };
457
458            let files_changed = {
459                let previous = match snapshot_for_callback.lock() {
460                    Ok(guard) => guard,
461                    Err(poisoned) => poisoned.into_inner(),
462                };
463                current_snapshot != *previous
464            };
465            if !files_changed {
466                // Still refresh watches when `lemma_deps/` or nested dirs appear.
467                let mut slot = match slot_for_callback.lock() {
468                    Ok(guard) => guard,
469                    Err(poisoned) => poisoned.into_inner(),
470                };
471                if let Some(debouncer) = slot.as_mut() {
472                    if let Err(error) = plant_watches(
473                        debouncer.watcher(),
474                        &workdir_for_callback,
475                        &watched_for_callback,
476                    ) {
477                        deliver(&on_change_for_callback, Err(error));
478                    }
479                }
480                return;
481            }
482
483            {
484                let mut previous = match snapshot_for_callback.lock() {
485                    Ok(guard) => guard,
486                    Err(poisoned) => poisoned.into_inner(),
487                };
488                *previous = current_snapshot;
489            }
490
491            deliver(&on_change_for_callback, Ok(()));
492
493            let mut slot = match slot_for_callback.lock() {
494                Ok(guard) => guard,
495                Err(poisoned) => poisoned.into_inner(),
496            };
497            if let Some(debouncer) = slot.as_mut() {
498                if let Err(error) = plant_watches(
499                    debouncer.watcher(),
500                    &workdir_for_callback,
501                    &watched_for_callback,
502                ) {
503                    deliver(&on_change_for_callback, Err(error));
504                }
505            }
506        },
507    )
508    .map_err(|error| WorkspaceDiskError::Io(std::io::Error::other(error)))?;
509
510    plant_watches(debouncer.watcher(), &workdir, &currently_watched)?;
511
512    {
513        let mut slot = match debouncer_slot.lock() {
514            Ok(guard) => guard,
515            Err(poisoned) => poisoned.into_inner(),
516        };
517        *slot = Some(debouncer);
518    }
519
520    Ok(WatchGuard {
521        debouncer: debouncer_slot,
522    })
523}
524
525/// Read all discovered `.lemma` files for LSP / tooling injection.
526pub fn read_disk_lemma_files(
527    workdir: &Path,
528) -> Result<Vec<lemma_lsp::workspace_files::DiskLemmaFile>, WorkspaceDiskError> {
529    let discovered = discover_lemma_paths(workdir)?;
530    let mut files = Vec::with_capacity(
531        discovered
532            .dependency_paths
533            .len()
534            .saturating_add(discovered.workspace_paths.len()),
535    );
536
537    for path in &discovered.dependency_paths {
538        let text = fs::read_to_string(path)?;
539        files.push(lemma_lsp::workspace_files::DiskLemmaFile {
540            path: path.clone(),
541            text,
542        });
543    }
544    for path in &discovered.workspace_paths {
545        let text = fs::read_to_string(path)?;
546        files.push(lemma_lsp::workspace_files::DiskLemmaFile {
547            path: path.clone(),
548            text,
549        });
550    }
551    Ok(files)
552}
553
554/// CLI implementation of [`lemma_lsp::workspace_files::WorkspaceFiles`].
555pub struct CliWorkspaceFiles;
556
557impl lemma_lsp::workspace_files::WorkspaceFiles for CliWorkspaceFiles {
558    fn load(
559        &self,
560        root: &Path,
561    ) -> Result<
562        Vec<lemma_lsp::workspace_files::DiskLemmaFile>,
563        lemma_lsp::workspace_files::WorkspaceFilesError,
564    > {
565        read_disk_lemma_files(root).map_err(|error| {
566            lemma_lsp::workspace_files::WorkspaceFilesError::new(error.to_string())
567        })
568    }
569
570    fn watch(
571        &self,
572        root: PathBuf,
573        on_change: Sender<
574            Result<
575                Vec<lemma_lsp::workspace_files::DiskLemmaFile>,
576                lemma_lsp::workspace_files::WorkspaceFilesError,
577            >,
578        >,
579    ) -> Result<
580        lemma_lsp::workspace_files::WatchGuard,
581        lemma_lsp::workspace_files::WorkspaceFilesError,
582    > {
583        let (watch_events, changes) = std::sync::mpsc::channel();
584        let guard = watch_lemma_workspace(root.clone(), watch_events).map_err(|error| {
585            lemma_lsp::workspace_files::WorkspaceFilesError::new(error.to_string())
586        })?;
587        std::thread::spawn(move || {
588            for watch_result in changes {
589                let event = match watch_result {
590                    Ok(()) => read_disk_lemma_files(&root).map_err(|error| {
591                        lemma_lsp::workspace_files::WorkspaceFilesError::new(error.to_string())
592                    }),
593                    Err(error) => Err(lemma_lsp::workspace_files::WorkspaceFilesError::new(
594                        error.to_string(),
595                    )),
596                };
597                deliver(&on_change, event);
598            }
599        });
600
601        Ok(lemma_lsp::workspace_files::WatchGuard::from_keep_alive(
602            Box::new(guard),
603        ))
604    }
605}
606
607#[cfg(test)]
608mod tests {
609    use super::*;
610    use std::fs;
611    use std::sync::atomic::{AtomicBool, Ordering};
612    use std::time::Duration;
613
614    fn flag_on_ok(
615        fired: Arc<AtomicBool>,
616    ) -> std::sync::mpsc::Sender<Result<(), WorkspaceDiskError>> {
617        let (sink, events) = std::sync::mpsc::channel::<Result<(), WorkspaceDiskError>>();
618        std::thread::spawn(move || {
619            for result in events {
620                if result.is_ok() {
621                    fired.store(true, Ordering::SeqCst);
622                }
623            }
624        });
625        sink
626    }
627
628    fn write_file(path: &Path, contents: &str) {
629        if let Some(parent) = path.parent() {
630            fs::create_dir_all(parent).expect("create parent");
631        }
632        fs::write(path, contents).expect("write file");
633    }
634
635    fn wait_until_fired(fired: &AtomicBool, message: &str) {
636        let deadline = std::time::Instant::now() + Duration::from_secs(3);
637        while std::time::Instant::now() < deadline {
638            if fired.load(Ordering::SeqCst) {
639                return;
640            }
641            std::thread::sleep(Duration::from_millis(50));
642        }
643        panic!("{message}");
644    }
645
646    #[test]
647    fn discover_excludes_gitignored_target_includes_lemma_deps() {
648        let root = tempfile::tempdir().expect("tempdir");
649        write_file(&root.path().join(".gitignore"), "/target\nlemma_deps/\n");
650        write_file(&root.path().join("src/app.lemma"), "spec app\ndata x: 1\n");
651        write_file(
652            &root.path().join("target/junk.lemma"),
653            "spec junk\ndata x: 1\n",
654        );
655        write_file(
656            &root.path().join("lemma_deps/@org/dep.lemma"),
657            "spec dep\ndata x: 1\n",
658        );
659
660        let discovered = discover_lemma_paths(root.path()).expect("discover");
661        assert_eq!(discovered.workspace_paths.len(), 1);
662        assert!(discovered.workspace_paths[0].ends_with("src/app.lemma"));
663        assert_eq!(discovered.dependency_paths.len(), 1);
664        assert!(discovered.dependency_paths[0].ends_with("lemma_deps/@org/dep.lemma"));
665    }
666
667    #[test]
668    fn load_workspace_stores_workdir_relative_path_labels() {
669        let root = tempfile::tempdir().expect("tempdir");
670        write_file(
671            &root.path().join("src/app.lemma"),
672            "spec app\ndata x: 1\nrule r: x\n",
673        );
674
675        let mut engine = Engine::new();
676        load_workspace(&mut engine, root.path()).expect("load");
677        let shown = engine
678            .show(None, "app", None)
679            .expect("app must show after load");
680        assert_eq!(
681            shown.source_type,
682            Some(lemma::SourceType::Path(std::sync::Arc::new(PathBuf::from(
683                "src/app.lemma"
684            )))),
685            "Engine Path identity must be workdir-relative, not absolute"
686        );
687    }
688
689    #[test]
690    fn refresh_resolves_consumer_that_sorts_before_provider() {
691        let root = tempfile::tempdir().expect("tempdir");
692        write_file(
693            &root.path().join("z_provider.lemma"),
694            "spec person\ndata name: \"Alice\"\n",
695        );
696        write_file(
697            &root.path().join("a_consumer.lemma"),
698            "spec company\nuses employee: person\n  -> with name: \"Bob\"\n",
699        );
700
701        let mut engine = Engine::new();
702        refresh_workspace_via_update(&mut engine, root.path()).expect("two-pass refresh");
703        assert!(engine.show(None, "person", None).is_ok());
704        assert!(engine.show(None, "company", None).is_ok());
705    }
706
707    #[test]
708    fn watch_fires_when_lemma_deps_file_appears() {
709        let root = tempfile::tempdir().expect("tempdir");
710        write_file(&root.path().join(".gitignore"), "lemma_deps/\n");
711        write_file(&root.path().join("src/app.lemma"), "spec app\ndata x: 1\n");
712        fs::create_dir_all(root.path().join("lemma_deps")).expect("create lemma_deps");
713
714        let fired = Arc::new(AtomicBool::new(false));
715        let fired_flag = Arc::clone(&fired);
716        let guard = watch_lemma_workspace(
717            root.path().to_path_buf(),
718            flag_on_ok(Arc::clone(&fired_flag)),
719        )
720        .expect("start watch");
721
722        write_file(
723            &root.path().join("lemma_deps/@org/dep.lemma"),
724            "spec dep\ndata x: 1\n",
725        );
726
727        wait_until_fired(&fired, "watch did not fire after creating lemma_deps file");
728        drop(guard);
729    }
730
731    #[test]
732    fn watch_does_not_fire_for_gitignored_target_lemma() {
733        let root = tempfile::tempdir().expect("tempdir");
734        write_file(&root.path().join(".gitignore"), "/target\n");
735        write_file(&root.path().join("src/app.lemma"), "spec app\ndata x: 1\n");
736        fs::create_dir_all(root.path().join("target")).expect("create target");
737
738        let fired = Arc::new(AtomicBool::new(false));
739        let fired_flag = Arc::clone(&fired);
740        let guard = watch_lemma_workspace(
741            root.path().to_path_buf(),
742            flag_on_ok(Arc::clone(&fired_flag)),
743        )
744        .expect("start watch");
745
746        write_file(
747            &root.path().join("target/junk.lemma"),
748            "spec junk\ndata x: 1\n",
749        );
750
751        std::thread::sleep(Duration::from_millis(800));
752        assert!(
753            !fired.load(Ordering::SeqCst),
754            "gitignored target/*.lemma must not change discover snapshot"
755        );
756        drop(guard);
757    }
758
759    #[test]
760    fn discover_snapshot_changes_when_content_changes_at_same_mtime() {
761        let root = tempfile::tempdir().expect("tempdir");
762        let app = root.path().join("src/app.lemma");
763        write_file(&app, "spec app\ndata x: 1\n");
764        let before = collect_discover_snapshot(root.path()).expect("snapshot");
765        write_file(&app, "spec app\ndata x: 2\n");
766        let after = collect_discover_snapshot(root.path()).expect("snapshot");
767        assert_ne!(
768            before, after,
769            "same-length rewrite must change the discover fingerprint even when mtime is unchanged"
770        );
771    }
772
773    #[test]
774    fn watch_fires_when_discovered_workspace_file_changes() {
775        let root = tempfile::tempdir().expect("tempdir");
776        let app = root.path().join("src/app.lemma");
777        write_file(&app, "spec app\ndata x: 1\n");
778
779        let fired = Arc::new(AtomicBool::new(false));
780        let fired_flag = Arc::clone(&fired);
781        let guard = watch_lemma_workspace(
782            root.path().to_path_buf(),
783            flag_on_ok(Arc::clone(&fired_flag)),
784        )
785        .expect("start watch");
786
787        write_file(&app, "spec app\ndata x: 2\n");
788
789        wait_until_fired(
790            &fired,
791            "watch did not fire after modifying discovered workspace file",
792        );
793        drop(guard);
794    }
795
796    #[test]
797    fn watch_fires_when_sibling_workspace_file_appears() {
798        let root = tempfile::tempdir().expect("tempdir");
799        write_file(&root.path().join("src/app.lemma"), "spec app\ndata x: 1\n");
800
801        let fired = Arc::new(AtomicBool::new(false));
802        let fired_flag = Arc::clone(&fired);
803        let guard = watch_lemma_workspace(
804            root.path().to_path_buf(),
805            flag_on_ok(Arc::clone(&fired_flag)),
806        )
807        .expect("start watch");
808
809        write_file(
810            &root.path().join("src/other.lemma"),
811            "spec other\ndata y: 2\n",
812        );
813
814        wait_until_fired(
815            &fired,
816            "watch did not fire after creating sibling workspace file",
817        );
818        drop(guard);
819    }
820
821    #[test]
822    fn watch_fires_when_nested_workspace_file_appears() {
823        let root = tempfile::tempdir().expect("tempdir");
824        write_file(&root.path().join("src/app.lemma"), "spec app\ndata x: 1\n");
825
826        let fired = Arc::new(AtomicBool::new(false));
827        let fired_flag = Arc::clone(&fired);
828        let guard = watch_lemma_workspace(
829            root.path().to_path_buf(),
830            flag_on_ok(Arc::clone(&fired_flag)),
831        )
832        .expect("start watch");
833
834        fs::create_dir_all(root.path().join("src/nested")).expect("create nested");
835        std::thread::sleep(Duration::from_millis(600));
836        write_file(
837            &root.path().join("src/nested/foo.lemma"),
838            "spec foo\ndata z: 3\n",
839        );
840
841        wait_until_fired(
842            &fired,
843            "watch did not fire after creating nested workspace file",
844        );
845        drop(guard);
846    }
847
848    #[test]
849    fn watch_plants_lemma_deps_after_directory_is_created() {
850        let root = tempfile::tempdir().expect("tempdir");
851        write_file(&root.path().join(".gitignore"), "lemma_deps/\n");
852        write_file(&root.path().join("src/app.lemma"), "spec app\ndata x: 1\n");
853
854        let fired = Arc::new(AtomicBool::new(false));
855        let fired_flag = Arc::clone(&fired);
856        let guard = watch_lemma_workspace(
857            root.path().to_path_buf(),
858            flag_on_ok(Arc::clone(&fired_flag)),
859        )
860        .expect("start watch");
861
862        fs::create_dir_all(root.path().join("lemma_deps")).expect("create lemma_deps");
863        std::thread::sleep(Duration::from_millis(600));
864        write_file(
865            &root.path().join("lemma_deps/@org/dep.lemma"),
866            "spec dep\ndata x: 1\n",
867        );
868
869        wait_until_fired(
870            &fired,
871            "watch did not fire after creating lemma_deps then a dep file",
872        );
873        drop(guard);
874    }
875
876    #[test]
877    fn watch_guard_drop_stops_further_callbacks() {
878        let root = tempfile::tempdir().expect("tempdir");
879        let app = root.path().join("src/app.lemma");
880        write_file(&app, "spec app\ndata x: 1\n");
881
882        let fired = Arc::new(AtomicBool::new(false));
883        let fired_flag = Arc::clone(&fired);
884        let guard = watch_lemma_workspace(
885            root.path().to_path_buf(),
886            flag_on_ok(Arc::clone(&fired_flag)),
887        )
888        .expect("start watch");
889
890        drop(guard);
891
892        write_file(&app, "spec app\ndata x: 2\n");
893        std::thread::sleep(Duration::from_millis(800));
894        assert!(
895            !fired.load(Ordering::SeqCst),
896            "dropped WatchGuard must stop notify callbacks"
897        );
898    }
899}