Skip to main content

lemma/
engine.rs

1use crate::evaluation::Evaluator;
2use crate::evaluation::{EvaluateData, EvaluateDataValue};
3use crate::literals::{DateGranularity, TimezoneValue};
4use crate::parsing::ast::{DateTimeValue, LemmaRepository, LemmaSpec};
5use crate::parsing::source::SourceType;
6use crate::parsing::{parse, EffectiveDate};
7use crate::planning::execution_plan::{ExecutionPlan, Show, ShowData};
8use crate::planning::semantics::{DataDefinition, DataPath, RulePath, SpecIdentity};
9use crate::planning::{LemmaSpecSet, PlanStore};
10use crate::{Error, ResourceLimits, Response};
11use indexmap::IndexMap;
12use std::collections::HashMap;
13use std::sync::Arc;
14
15/// Load failure: errors plus the source texts we attempted to load.
16#[derive(Debug, Clone)]
17pub struct Errors {
18    pub errors: Vec<Error>,
19    pub sources: HashMap<SourceType, String>,
20}
21
22impl Errors {
23    /// Iterate over the errors.
24    pub fn iter(&self) -> std::slice::Iter<'_, Error> {
25        self.errors.iter()
26    }
27}
28
29/// Resolve an optional effective datetime string for planning or evaluation.
30///
31/// `None` or whitespace-only input resolves to [`DateTimeValue::now`].
32/// Non-empty invalid strings return a request [`Error`].
33///
34/// Date-only forms (`YYYY`, `YYYY-MM`, `YYYY-MM-DD`, ISO week) become a precise
35/// UTC instant at the start of that period (`00:00:00Z`, [`DateGranularity::DateTime`]).
36/// Full ISO datetimes keep their parsed clock and timezone.
37pub fn resolve_effective(raw: Option<&str>) -> Result<DateTimeValue, Error> {
38    match raw {
39        Some(s) if !s.trim().is_empty() => {
40            let parsed = s.trim().parse::<DateTimeValue>().map_err(|_| {
41                Error::request(
42                    format!(
43                        "Invalid effective value '{}'. Expected: YYYY, YYYY-MM, YYYY-MM-DD, or ISO 8601 datetime",
44                        s.trim()
45                    ),
46                    None::<String>,
47                )
48            })?;
49            Ok(promote_effective_to_instant(parsed))
50        }
51        _ => Ok(DateTimeValue::now()),
52    }
53}
54
55/// Date-only parse results keep calendar granularity; the evaluation instant always
56/// needs a clock. Promote to UTC midnight at the already-normalized calendar day.
57fn promote_effective_to_instant(mut dt: DateTimeValue) -> DateTimeValue {
58    if matches!(dt.granularity, DateGranularity::DateTime) {
59        return dt;
60    }
61    dt.hour = 0;
62    dt.minute = 0;
63    dt.second = 0;
64    dt.microsecond = 0;
65    dt.timezone = Some(TimezoneValue { offset_minutes: 0 });
66    dt.granularity = DateGranularity::DateTime;
67    dt
68}
69
70/// Repository name reserved for the embedded standard library (`repo lemma`, `spec units`).
71/// User [`Engine::load`] must not target this name via [`SourceType::Dependency`].
72pub const EMBEDDED_STDLIB_REPOSITORY: &str = "lemma";
73
74/// One `uses` target from a spec version's source.
75#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
76pub struct SpecDependency {
77    #[serde(skip_serializing_if = "Option::is_none")]
78    pub repository: Option<String>,
79    pub name: String,
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub effective: Option<DateTimeValue>,
82}
83
84impl std::fmt::Display for SpecDependency {
85    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86        if let Some(repository) = &self.repository {
87            write!(f, "{repository} ")?;
88        }
89        write!(f, "{}", self.name)?;
90        if let Some(effective) = &self.effective {
91            write!(f, " {effective}")?;
92        }
93        Ok(())
94    }
95}
96
97/// One temporal spec version from [`Engine::specs`].
98#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
99pub struct SpecVersion {
100    pub name: String,
101    #[serde(skip_serializing_if = "Option::is_none")]
102    pub effective_from: Option<DateTimeValue>,
103    #[serde(skip_serializing_if = "Option::is_none")]
104    pub effective_to: Option<DateTimeValue>,
105    #[serde(skip_serializing_if = "Vec::is_empty")]
106    pub dependencies: Vec<SpecDependency>,
107}
108
109/// Half-open window as `lemma specs` / `lemma show` print it, same `lo...hi`
110/// notation as range values. Open start is `...to`; open end is the start date
111/// alone (matches `spec name date`); both absent prints nothing.
112pub(crate) fn write_effective_window(
113    f: &mut impl std::fmt::Write,
114    from: Option<&DateTimeValue>,
115    to: Option<&DateTimeValue>,
116) -> std::fmt::Result {
117    match (from, to) {
118        (Some(from), Some(to)) => write!(f, " {from}...{to}"),
119        (Some(from), None) => write!(f, " {from}"),
120        (None, Some(to)) => write!(f, " ...{to}"),
121        (None, None) => Ok(()),
122    }
123}
124
125impl std::fmt::Display for SpecVersion {
126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        f.write_str(&self.name)?;
128        write_effective_window(f, self.effective_from.as_ref(), self.effective_to.as_ref())
129    }
130}
131
132/// Repository group from [`Engine::specs`].
133///
134/// [`Self::repository`] is absent for the default unnamed repository.
135/// [`Self::from_dependency`] is true for lemma_deps and the embedded stdlib;
136/// it is omitted from JSON.
137#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
138pub struct Repository {
139    #[serde(skip_serializing_if = "Option::is_none")]
140    pub repository: Option<String>,
141    pub specs: Vec<SpecVersion>,
142    #[serde(skip)]
143    pub from_dependency: bool,
144}
145
146/// Text view of [`Engine::specs`], as `lemma specs` prints it.
147///
148/// `all == false` (`lemma specs`): local repositories only (not lemma_deps / embedded
149/// stdlib). Each temporal version is followed by its `uses` targets, indented.
150/// `all == true` (`lemma specs --all`): every loaded repository; names and windows only.
151///
152/// Version lines are `name` plus ` from...to`, ` from`, ` ...to`, or the name alone,
153/// sorted by name then `effective_from`. The unnamed repository's rows are unindented;
154/// a named repository is a header with indented rows. Repositories without specs are
155/// left out; groups are separated by a blank line.
156#[must_use]
157pub fn format_repositories(repositories: &[Repository], all: bool) -> String {
158    let mut output = String::new();
159    let groups = repositories
160        .iter()
161        .filter(|resolved| !resolved.specs.is_empty() && (all || !resolved.from_dependency));
162    for (index, resolved) in groups.enumerate() {
163        if index > 0 {
164            output.push('\n');
165        }
166        let mut versions: Vec<&SpecVersion> = resolved.specs.iter().collect();
167        versions.sort_by(|a, b| (&a.name, &a.effective_from).cmp(&(&b.name, &b.effective_from)));
168        let indent = match resolved.repository.as_deref() {
169            None => "",
170            Some(repository) => {
171                output.push_str(repository);
172                output.push('\n');
173                "  "
174            }
175        };
176        for version in versions {
177            output.push_str(indent);
178            output.push_str(&version.to_string());
179            output.push('\n');
180            if !all {
181                for dependency in &version.dependencies {
182                    output.push_str(indent);
183                    output.push_str("  ");
184                    output.push_str(&dependency.to_string());
185                    output.push('\n');
186                }
187            }
188        }
189    }
190    output
191}
192
193fn uses_dependencies(spec: &LemmaSpec) -> Vec<SpecDependency> {
194    spec.data
195        .iter()
196        .filter_map(|data| {
197            data.value.uses_spec_ref().map(|spec_ref| SpecDependency {
198                repository: spec_ref.repository.as_ref().map(|q| q.name.clone()),
199                name: spec_ref.name.clone(),
200                effective: spec_ref.effective.clone(),
201            })
202        })
203        .collect()
204}
205
206// ─── Spec store with temporal resolution ──────────────────────────────
207
208/// Ordered store of specs keyed by `(repository, name)` and grouped into
209/// [`LemmaSpecSet`]s.
210///
211/// Specs with the same `(repository, name)` identity are ordered by `effective_from`.
212/// A spec version's temporal end is derived from the successor spec's `effective_from`, or
213/// `+∞`. The repository identity is preserved as `Arc<LemmaRepository>` — never via string
214/// prefixes on the spec name. Repository names include the `@` prefix when present
215/// (e.g. `"@org/repo"`). Dependency isolation is enforced at `insert_spec`: all specs
216/// in a repository must share the same `dependency` provenance ID.
217#[derive(Debug)]
218pub struct Context {
219    repositories: IndexMap<Arc<LemmaRepository>, IndexMap<String, LemmaSpecSet>>,
220    workspace: Arc<LemmaRepository>,
221}
222
223impl Default for Context {
224    fn default() -> Self {
225        Self::new()
226    }
227}
228
229impl Context {
230    /// Empty default repository; specs are inserted via [`Self::insert_spec`].
231    pub fn new() -> Self {
232        let workspace = Arc::new(LemmaRepository::new(None));
233        let mut repositories = IndexMap::new();
234        repositories.insert(Arc::clone(&workspace), IndexMap::new());
235        Self {
236            repositories,
237            workspace,
238        }
239    }
240
241    /// Default unnamed repository. Runtime APIs with `repository: None` use this.
242    /// Stable identity; `name = None`, `dependency = None`.
243    #[must_use]
244    pub fn workspace(&self) -> Arc<LemmaRepository> {
245        Arc::clone(&self.workspace)
246    }
247
248    /// Look up a repository by name without creating a new one.
249    #[must_use]
250    pub fn find_repository(&self, name: &str) -> Option<Arc<LemmaRepository>> {
251        let canonical = crate::parsing::ast::canonical_logical_name(name);
252        self.repositories
253            .keys()
254            .find(|repo| repo.name.as_deref() == Some(canonical.as_ref()))
255            .cloned()
256    }
257
258    /// All spec sets, keyed by `(repository, name)`. Iteration order: repository first
259    /// (insertion order), then spec name ascending.
260    #[must_use]
261    pub fn repositories(&self) -> &IndexMap<Arc<LemmaRepository>, IndexMap<String, LemmaSpecSet>> {
262        &self.repositories
263    }
264
265    /// Flat iterator over every loaded [`LemmaSpec`] across all repositories.
266    ///
267    /// Used by registry resolution to discover missing `@owner/repo` qualifiers.
268    pub fn iter(&self) -> impl Iterator<Item = &LemmaSpec> + '_ {
269        self.repositories
270            .values()
271            .flat_map(|m| m.values())
272            .flat_map(|ss| ss.iter_specs())
273    }
274
275    /// Look up a spec set by `(repository, name)`. Returns `None` if no such spec set
276    /// is loaded.
277    #[must_use]
278    pub fn spec_set(&self, repository: &Arc<LemmaRepository>, name: &str) -> Option<&LemmaSpecSet> {
279        let canonical_name = crate::parsing::ast::canonical_logical_name(name);
280        self.repositories
281            .get(repository)
282            .and_then(|m| m.get(canonical_name.as_ref()))
283    }
284
285    /// Spec sets belonging to a repository. Panics if the repository is not in the map
286    /// (caller must ensure it was returned by this Context).
287    pub(crate) fn spec_sets_for(
288        &self,
289        repository: &Arc<LemmaRepository>,
290    ) -> impl Iterator<Item = &LemmaSpecSet> + '_ {
291        self.repositories
292            .get(repository)
293            .expect("BUG: repository not in context")
294            .values()
295    }
296
297    fn spec_declaration_source(spec: &LemmaSpec) -> crate::parsing::source::Source {
298        let source_type = spec
299            .source_type
300            .as_ref()
301            .expect("BUG: spec must carry source_type after parse");
302        crate::parsing::source::Source::new(
303            source_type.clone(),
304            crate::parsing::ast::Span {
305                start: 0,
306                end: 0,
307                line: spec.start_line,
308                col: 0,
309            },
310        )
311    }
312
313    fn duplicate_spec_path_line(spec: &LemmaSpec) -> (String, usize) {
314        let source_type = spec
315            .source_type
316            .as_ref()
317            .expect("BUG: spec must carry source_type after parse");
318        (source_type.to_string(), spec.start_line)
319    }
320
321    fn duplicate_spec_errors(name: &str, incoming: &LemmaSpec, existing: &LemmaSpec) -> Vec<Error> {
322        let (incoming_path, incoming_line) = Self::duplicate_spec_path_line(incoming);
323        let (existing_path, existing_line) = Self::duplicate_spec_path_line(existing);
324        vec![
325            Error::validation(
326                format!(
327                    "Duplicate spec '{name}' (also declared in '{existing_path}':{existing_line})"
328                ),
329                Some(Self::spec_declaration_source(incoming)),
330                None::<String>,
331            ),
332            Error::validation(
333                format!(
334                    "Duplicate spec '{name}' (also declared in '{incoming_path}':{incoming_line})"
335                ),
336                Some(Self::spec_declaration_source(existing)),
337                None::<String>,
338            ),
339        ]
340    }
341
342    /// Insert a spec under `repository`. Enforces two invariants:
343    /// 1. Dependency isolation: all specs in a repo must share the same `dependency`
344    ///    provenance. A locally loaded repo cannot be merged with a dependency repo, and
345    ///    two different dependencies cannot contribute to the same repo name.
346    /// 2. No duplicate `(repository, name, effective_from)` triples.
347    ///
348    /// A repository already in the context keeps its `Arc`: the spec set holds that one,
349    /// not the header of the source being inserted.
350    pub fn insert_spec(
351        &mut self,
352        repository: Arc<LemmaRepository>,
353        spec: LemmaSpec,
354    ) -> Result<(), Vec<Error>> {
355        self.insert_spec_replacing(repository, spec, None)
356    }
357
358    /// [`Self::insert_spec`] for a spec that replaces a version taken out by
359    /// [`Self::take_spec`]: an equal spec keeps the replaced version's `Arc`
360    /// ([`LemmaSpecSet::insert_replacing`]).
361    pub(crate) fn insert_spec_replacing(
362        &mut self,
363        repository: Arc<LemmaRepository>,
364        spec: LemmaSpec,
365        replaced: Option<Arc<LemmaSpec>>,
366    ) -> Result<(), Vec<Error>> {
367        let repository = match self.repositories.get_key_value(&repository) {
368            None => repository,
369            Some((existing_repo, _)) => {
370                if existing_repo.dependency != repository.dependency {
371                    let repo_subject = match repository.name.as_deref() {
372                        Some(name) => format!("Repository '{name}'"),
373                        None => "The default repository".to_string(),
374                    };
375                    let existing_owner = match &existing_repo.dependency {
376                        None => "a local source".to_string(),
377                        Some(id) => format!("dependency '{id}'"),
378                    };
379                    let new_owner = match &repository.dependency {
380                        None => "a local source".to_string(),
381                        Some(id) => format!("dependency '{id}'"),
382                    };
383                    return Err(vec![Error::validation_with_context(
384                    format!(
385                        "{repo_subject} was introduced by {existing_owner} but {new_owner} also declares it"
386                    ),
387                    None,
388                    Some("Each dependency's repositories must be unique across all loaded sources"),
389                    Some(&spec),
390                    None,
391                )]);
392                }
393                Arc::clone(existing_repo)
394            }
395        };
396
397        let entry = self
398            .repositories
399            .entry(Arc::clone(&repository))
400            .or_default();
401        if let Some(ss) = entry.get(&spec.name) {
402            if let Some(existing) = ss.get_exact(spec.effective_from()) {
403                return Err(Self::duplicate_spec_errors(&spec.name, &spec, existing));
404            }
405        }
406
407        let name = spec.name.clone();
408        if !entry
409            .entry(name.clone())
410            .or_insert_with(|| LemmaSpecSet::new(repository, name))
411            .insert_replacing(spec, replaced)
412        {
413            unreachable!("BUG: duplicate effective_from rejected above");
414        }
415        Ok(())
416    }
417
418    /// Rollback insertion of a version removed by [`Self::take_spec`], keeping the
419    /// removed `Arc` so plans that reference it stay shared.
420    pub(crate) fn insert_spec_replacing_owned(
421        &mut self,
422        repository: Arc<LemmaRepository>,
423        spec: Arc<LemmaSpec>,
424    ) -> Result<(), Vec<Error>> {
425        let name = spec.name.clone();
426        let effective_from = spec.effective_from.clone();
427        if self
428            .spec_set(&repository, &name)
429            .is_some_and(|ss| ss.get_exact(effective_from.as_ref()).is_some())
430        {
431            panic!("BUG: rollback insert found a live spec at the removed identity");
432        }
433        let entry = self.repositories.entry(repository.clone()).or_default();
434        entry
435            .entry(name.clone())
436            .or_insert_with(|| LemmaSpecSet::new(repository, name))
437            .insert_owned(spec);
438        Ok(())
439    }
440
441    pub fn remove_spec(&mut self, repository: &Arc<LemmaRepository>, spec: &LemmaSpec) -> bool {
442        self.remove_spec_by_identity(repository, &spec.name, spec.effective_from())
443    }
444
445    /// Remove by `(repository, name, effective_from)` without needing a live `&LemmaSpec`.
446    pub fn remove_spec_by_identity(
447        &mut self,
448        repository: &Arc<LemmaRepository>,
449        name: &str,
450        effective_from: Option<&DateTimeValue>,
451    ) -> bool {
452        self.take_spec(repository, name, effective_from).is_some()
453    }
454
455    /// Drop every named repository that holds no spec, keeping the order of the rest. The
456    /// default repository always exists. A batch prunes only after it commits, so a
457    /// rollback finds every repository it emptied still in place.
458    pub(crate) fn remove_empty_repositories(&mut self) {
459        let workspace = Arc::clone(&self.workspace);
460        self.repositories
461            .retain(|repository, by_name| !by_name.is_empty() || *repository == workspace);
462    }
463
464    /// Remove by `(repository, name, effective_from)`, returning the removed spec `Arc`.
465    pub(crate) fn take_spec(
466        &mut self,
467        repository: &Arc<LemmaRepository>,
468        name: &str,
469        effective_from: Option<&DateTimeValue>,
470    ) -> Option<Arc<LemmaSpec>> {
471        let inner = self.repositories.get_mut(repository)?;
472        let ss = inner.get_mut(name)?;
473        let removed = ss.take(effective_from)?;
474        if ss.is_empty() {
475            inner.shift_remove(name);
476        }
477        Some(removed)
478    }
479}
480
481// ─── Engine ──────────────────────────────────────────────────────────
482
483/// One mutation in a transactional [`Engine::apply`] batch.
484///
485/// Removes are applied before loads/replaces so identity swaps cannot hit the
486/// duplicate-spec error or a mid-batch missing-dep replan. A batch is only
487/// `Remove`s, only `Load`s, or a single `Replace` — never `Load` mixed with `Replace`.
488enum Mutation {
489    Remove {
490        repository: Option<String>,
491        spec: String,
492        effective_from: EffectiveDate,
493    },
494    Load {
495        source_type: SourceType,
496        code: String,
497    },
498    /// Identity upsert from `code`, then prune other live specs with this
499    /// `source_type` when it is [`SourceType::Path`] or [`SourceType::Dependency`].
500    Replace {
501        repository: Option<String>,
502        source_type: SourceType,
503        code: String,
504    },
505}
506
507type StagedSpec = (SourceType, Arc<LemmaRepository>, LemmaSpec);
508
509/// A version taken out of the context by a batch, kept until the batch commits or rolls
510/// back. Its `Arc` goes to the spec that replaces it, or back on rollback.
511struct RemovedSpec {
512    repository: Arc<LemmaRepository>,
513    spec: Arc<LemmaSpec>,
514}
515
516/// Engine for evaluating Lemma rules.
517///
518/// Pure Rust implementation that evaluates Lemma specs directly from the AST.
519/// Uses pre-built execution plans that are self-contained and ready for evaluation.
520///
521/// The engine never performs network calls. External `@` references must be
522/// pre-resolved (include dependency sources in the source map, or drive
523/// [`crate::Resolve`] with a host [`crate::HttpTransport`]) before loading.
524pub struct Engine {
525    pub(crate) context: Context,
526    pub(crate) plans: PlanStore,
527    limits: ResourceLimits,
528}
529
530impl Default for Engine {
531    fn default() -> Self {
532        Self::new()
533    }
534}
535
536impl Engine {
537    pub fn new() -> Self {
538        Self::with_limits(ResourceLimits::default())
539    }
540
541    pub fn with_limits(limits: ResourceLimits) -> Self {
542        let mut engine = Self {
543            context: Context::new(),
544            plans: PlanStore::new(),
545            limits,
546        };
547        engine
548            .apply(
549                vec![Mutation::Load {
550                    source_type: SourceType::Dependency(EMBEDDED_STDLIB_REPOSITORY.to_string()),
551                    code: crate::stdlib::UNITS_LEMMA.to_string(),
552                }],
553                true,
554            )
555            .expect("BUG: embedded stdlib must load");
556        engine
557    }
558
559    /// Resource limits configured for this engine.
560    pub fn limits(&self) -> &ResourceLimits {
561        &self.limits
562    }
563
564    /// Instance-list row store row counts and Arc pointers by path for `spec`.
565    ///
566    /// Each entry is `(path, row_count, Arc::as_ptr of the row store as usize)`.
567    /// Diagnostic for Load-cost investigation. Not a supported consumer API.
568    #[doc(hidden)]
569    pub fn debug_instance_list_row_counts(
570        &self,
571        repository: Option<&str>,
572        spec: &str,
573    ) -> Vec<(String, usize, usize)> {
574        let Some(plan) = self.plans.get_plan(
575            repository,
576            spec,
577            &EffectiveDate::DateTimeValue(DateTimeValue::now()),
578        ) else {
579            return Vec::new();
580        };
581        let mut rows: Vec<(String, usize, usize)> = plan
582            .instance_lists
583            .iter()
584            .map(|(path, source)| {
585                (
586                    path.data.clone(),
587                    source.store.rows.len(),
588                    Arc::as_ptr(&source.store) as usize,
589                )
590            })
591            .collect();
592        rows.sort_by(|left, right| left.0.cmp(&right.0));
593        rows
594    }
595
596    /// Named-`uses` / list row-template Arc pointers for `spec`.
597    ///
598    /// Each entry is `(holder, identity, Arc::as_ptr as usize)`. `holder` is empty
599    /// for templates on `spec`'s plan; otherwise it is the template identity that
600    /// owns the nested entry (one level). Diagnostic for Load-cost investigation.
601    /// Not a supported consumer API.
602    #[doc(hidden)]
603    pub fn debug_row_template_arc_ptrs(
604        &self,
605        repository: Option<&str>,
606        spec: &str,
607    ) -> Vec<(String, String, usize)> {
608        let Some(plan) = self.plans.get_plan(
609            repository,
610            spec,
611            &EffectiveDate::DateTimeValue(DateTimeValue::now()),
612        ) else {
613            return Vec::new();
614        };
615        let mut rows = Vec::new();
616        for (identity, template) in &plan.row_templates {
617            let identity_label = identity.to_string();
618            rows.push((
619                String::new(),
620                identity_label.clone(),
621                std::sync::Arc::as_ptr(template) as usize,
622            ));
623            for (nested_id, nested) in &template.row_templates {
624                rows.push((
625                    identity_label.clone(),
626                    nested_id.to_string(),
627                    std::sync::Arc::as_ptr(nested) as usize,
628                ));
629            }
630        }
631        rows.sort_by(|left, right| left.0.cmp(&right.0).then(left.1.cmp(&right.1)));
632        rows
633    }
634
635    /// Load Lemma sources in one planning pass. Pairs are `(source_type, source_text)`.
636    ///
637    /// Provenance is derived solely from [`SourceType`]: [`SourceType::Path`] and
638    /// [`SourceType::Volatile`] are local; [`SourceType::Dependency`] tags
639    /// repositories with that dependency id.
640    pub fn load(
641        &mut self,
642        sources: impl IntoIterator<Item = (SourceType, impl Into<String>)>,
643    ) -> Result<(), Errors> {
644        let mutations = sources
645            .into_iter()
646            .map(|(source_type, code)| Mutation::Load {
647                source_type,
648                code: code.into(),
649            })
650            .collect();
651        self.apply(mutations, false)
652    }
653
654    /// Replace identities present in `code` in a single planning pass.
655    ///
656    /// Parses `code` under `source_type`. Each parsed identity is inserted or
657    /// replaced by exact `(repository, name, effective_from)`. For
658    /// [`SourceType::Path`] and [`SourceType::Dependency`], live specs with the
659    /// same `source_type` that are absent from `code` are removed in the same
660    /// apply — including when `code` has zero specs (remove every live row of
661    /// that source). [`SourceType::Volatile`] never prunes siblings and requires
662    /// at least one spec in `code`.
663    ///
664    /// When `repository` is `Some(name)`, every staged spec's repository name must
665    /// equal `name`.
666    pub fn update(
667        &mut self,
668        repository: Option<&str>,
669        code: String,
670        source_type: SourceType,
671    ) -> Result<(), Errors> {
672        self.apply(
673            vec![Mutation::Replace {
674                repository: repository.map(str::to_string),
675                source_type,
676                code,
677            }],
678            false,
679        )
680    }
681
682    /// Remove a temporal spec slice and replan remaining specs.
683    pub fn remove(
684        &mut self,
685        repository: Option<&str>,
686        spec: &str,
687        effective: Option<&DateTimeValue>,
688    ) -> Result<(), Error> {
689        let resolved = self.get_spec(spec, repository, effective)?;
690        let effective_from = resolved.effective_from.clone();
691        self.apply(
692            vec![Mutation::Remove {
693                repository: repository.map(str::to_string),
694                spec: spec.to_string(),
695                effective_from,
696            }],
697            false,
698        )
699        .map_err(|errs| {
700            errs.errors
701                .into_iter()
702                .next()
703                .expect("BUG: apply Errors must contain at least one error")
704        })
705    }
706
707    /// Every loaded repository in insertion order (default unnamed repository, embedded stdlib [`EMBEDDED_STDLIB_REPOSITORY`], dependencies).
708    ///
709    /// Returns spec version rows (metadata only, no AST, no source text).
710    #[must_use]
711    pub fn specs(&self) -> Vec<Repository> {
712        self.context
713            .repositories()
714            .iter()
715            .map(|(repo, inner)| {
716                let specs = inner
717                    .values()
718                    .flat_map(|spec_set| {
719                        spec_set
720                            .iter_with_ranges()
721                            .map(|(spec, from, to)| SpecVersion {
722                                name: spec.name.clone(),
723                                effective_from: from,
724                                effective_to: to,
725                                dependencies: uses_dependencies(spec),
726                            })
727                    })
728                    .collect();
729                Repository {
730                    repository: repo.name.clone(),
731                    specs,
732                    from_dependency: repo.dependency.is_some(),
733                }
734            })
735            .collect()
736    }
737
738    /// Spec interface and resolved temporal window at `effective`.
739    ///
740    /// Covering execution plan for `spec` at `effective` (or now).
741    ///
742    /// Same attributed miss path as [`Self::show`]: repository not loaded, spec not
743    /// found at that instant, or no plan slice after a successful load.
744    pub fn plan(
745        &self,
746        repository: Option<&str>,
747        spec: &str,
748        effective: Option<&DateTimeValue>,
749    ) -> Result<&ExecutionPlan, Error> {
750        let effective_dt = self.effective_or_now(effective);
751        let instant = EffectiveDate::DateTimeValue(effective_dt.clone());
752
753        match self.plans.get_plan(repository, spec, &instant) {
754            Some(plan) => Ok(plan),
755            None => {
756                let repository_arc = self.repository_for_lookup(repository)?;
757                let canonical_name =
758                    crate::parsing::ast::ascii_lowercase_logical_name(spec.to_string());
759                let spec_set = self.context.spec_set(&repository_arc, &canonical_name);
760                match spec_set.and_then(|ss| ss.spec_at(&instant)) {
761                    None => Err(self.spec_not_found_in_repository_error(
762                        &repository_arc,
763                        spec,
764                        &effective_dt,
765                    )),
766                    Some(_) => Err(Error::request_not_found(
767                        format!(
768                            "No execution plan slice for spec '{spec}' at effective {effective_dt}"
769                        ),
770                        Some("Ensure sources loaded and planning succeeded".to_string()),
771                    )),
772                }
773            }
774        }
775    }
776
777    /// `Show.data` lists every declared promptable slot. Empty
778    /// [`ShowData::needed_by_rules`] means offered for reuse (`data x: alias.slot`),
779    /// not needed by this spec's remaining rules after normalize.
780    /// Lemma source text is [`Self::source`].
781    pub fn show(
782        &self,
783        repository: Option<&str>,
784        spec: &str,
785        effective: Option<&DateTimeValue>,
786    ) -> Result<Show, Error> {
787        let plan = self.plan(repository, spec, effective)?;
788        Ok(self.show_plan(plan, repository))
789    }
790
791    /// Declarations of `spec` at `effective` as loaded from source, including data and
792    /// rules that no other rule needs. Unlike [`Self::show`], nothing is filtered by use.
793    pub fn spec_declaration(
794        &self,
795        repository: Option<&str>,
796        spec: &str,
797        effective: Option<&DateTimeValue>,
798    ) -> Result<&LemmaSpec, Error> {
799        let effective_dt = self.effective_or_now(effective);
800        let instant = EffectiveDate::DateTimeValue(effective_dt.clone());
801        let repository_arc = self.repository_for_lookup(repository)?;
802        let canonical_name = crate::parsing::ast::ascii_lowercase_logical_name(spec.to_string());
803        match self
804            .context
805            .spec_set(&repository_arc, &canonical_name)
806            .and_then(|spec_set| spec_set.spec_at(&instant))
807        {
808            Some(found) => Ok(found),
809            None => {
810                Err(self.spec_not_found_in_repository_error(&repository_arc, spec, &effective_dt))
811            }
812        }
813    }
814
815    /// Interface of the resolved spec slice `identity` names, e.g. the row spec of a list
816    /// type. Identities come from loaded plans, so the plan exists.
817    pub fn show_spec(&self, identity: &SpecIdentity) -> Show {
818        let plan = self
819            .plans
820            .get_plan(
821                identity.repository.as_deref(),
822                &identity.spec,
823                &identity.slice,
824            )
825            .unwrap_or_else(|| panic!("BUG: no plan for resolved spec '{identity}'"));
826        self.show_plan(plan, identity.repository.as_deref())
827    }
828
829    /// Plan that produced `show` (repo + spec + start line + slice effective).
830    /// `None` when no plans are loaded for that spec (synthetic Show in tests).
831    pub(crate) fn plan_matching_show(
832        &self,
833        show: &crate::planning::execution_plan::Show,
834    ) -> Option<&crate::planning::execution_plan::ExecutionPlan> {
835        let plans = self
836            .plans
837            .get_plans(show.repository.as_deref(), &show.spec)?;
838        let mut matches = plans.values().filter(|plan| {
839            plan.spec_name == show.spec
840                && plan.start_line == show.start_line
841                && plan.effective_from == show.effective_from
842                && plan.effective_to == show.effective_to
843                && plan.effective == show.plan_effective
844        });
845        let first = matches.next()?;
846        if matches.next().is_some() {
847            panic!(
848                "BUG: multiple plans match Show '{}' (start_line {}, effective window, plan_effective)",
849                show.spec, show.start_line
850            );
851        }
852        Some(first)
853    }
854
855    fn show_plan(&self, plan: &ExecutionPlan, repository: Option<&str>) -> Show {
856        let mut type_entries: Vec<(usize, String, crate::planning::semantics::LemmaType)> =
857            Vec::new();
858        let mut data_entries: Vec<(usize, usize, String, ShowData)> = Vec::new();
859
860        for (path, definition) in plan.input_slots() {
861            let Some(lemma_type) = definition.schema_type().cloned() else {
862                continue;
863            };
864            let input_key = path.input_key();
865            if matches!(
866                definition,
867                DataDefinition::Value { .. }
868                    | DataDefinition::TypeDeclaration { .. }
869                    | DataDefinition::Reference { .. }
870            ) {
871                type_entries.push((
872                    definition.source().span.start,
873                    input_key.clone(),
874                    lemma_type.clone(),
875                ));
876            }
877            // A slot the spec bound (`uses -> with`, a row field) is not promptable.
878            if definition.is_bound() {
879                continue;
880            }
881            data_entries.extend(Self::show_data_entry(plan, path, path, definition));
882        }
883        for (path, identity) in &plan.show_import_data {
884            let template = plan.row_template(identity);
885            let local = DataPath::local(path.data.clone());
886            let definition = template.data.get(&local).unwrap_or_else(|| {
887                panic!(
888                    "BUG: Show import data '{path}' missing from template '{}'",
889                    template.spec_name
890                )
891            });
892            data_entries.extend(Self::show_data_entry(plan, path, &local, definition).map(
893                |(depth, position, name, mut entry)| {
894                    if let DataDefinition::InstanceList { .. } = definition {
895                        entry.value = crate::planning::execution_plan::show_instance_list_value(
896                            template, &local,
897                        );
898                    }
899                    (depth, position, name, entry)
900                },
901            ));
902        }
903        type_entries.sort_by_key(|(pos, _, _)| *pos);
904        data_entries.sort_by_key(|(depth, pos, _, _)| (*depth, *pos));
905
906        let rule_entries: Vec<(String, crate::planning::show_expression::ShowRule)> = plan
907            .show_rules
908            .iter()
909            .map(|(path, rule)| (path.input_key(), rule.clone()))
910            .collect();
911
912        let show_repository = match repository {
913            None => None,
914            Some(q) => {
915                let repo = self
916                    .context
917                    .find_repository(q)
918                    .expect("BUG: get_plan succeeded so that repository must be loaded");
919                Some(
920                    repo.name
921                        .clone()
922                        .expect("BUG: named repository cannot have name None"),
923                )
924            }
925        };
926
927        Show {
928            repository: show_repository,
929            spec: plan.spec_name.clone(),
930            commentary: plan.commentary.clone(),
931            effective_from: plan.effective_from.clone(),
932            effective_to: plan.effective_to.clone(),
933            plan_effective: plan.effective.clone(),
934            start_line: plan.start_line,
935            source_type: plan.source_type.clone(),
936            types: type_entries
937                .into_iter()
938                .map(|(_, name, lemma_type)| (name, lemma_type))
939                .collect(),
940            data: data_entries
941                .into_iter()
942                .map(|(_, _, name, entry)| (name, entry))
943                .collect(),
944            rules: rule_entries.into_iter().collect(),
945            meta: plan.meta.clone(),
946        }
947    }
948
949    /// Show entry of data `path` (composed from `uses` hops) of `plan`, defined as
950    /// `local` by `definition` in the plan that declares it; `None` when no Show rule
951    /// needs it.
952    fn show_data_entry(
953        plan: &ExecutionPlan,
954        path: &DataPath,
955        local: &DataPath,
956        definition: &DataDefinition,
957    ) -> Option<(usize, usize, String, ShowData)> {
958        let declaring = match plan.show_import_data.get(path) {
959            Some(identity) => plan.row_template(identity),
960            None => plan,
961        };
962        let lemma_type = definition
963            .schema_type()
964            .expect("BUG: promptable Show data has a schema type")
965            .clone();
966        let input_key = path.input_key();
967        let local_readers = plan
968            .data
969            .get_index_of(path)
970            .map(|data_pos| plan.needed_by_rules[data_pos].rules.as_slice())
971            .unwrap_or_default()
972            .iter()
973            .map(|&position| {
974                plan.rules
975                    .get_index(position as usize)
976                    .expect("BUG: needed_by_rules position out of plan.rules range")
977                    .0
978            });
979        let show_readers = plan
980            .show_needed_by
981            .get(path)
982            .map(Vec::as_slice)
983            .unwrap_or_default()
984            .iter()
985            .map(|&position| {
986                plan.show_rules
987                    .get_index(position as usize)
988                    .expect("BUG: show_needed_by position out of show_rules range")
989                    .0
990            });
991        let mut used_by: Vec<String> = local_readers
992            .chain(show_readers)
993            .map(RulePath::input_key)
994            .collect();
995        if used_by.is_empty() {
996            return None;
997        }
998        used_by.sort();
999        let display = declaring.data_display.get(local);
1000        Some((
1001            path.segments.len(),
1002            definition.source().span.start,
1003            input_key.clone(),
1004            ShowData {
1005                lemma_type: lemma_type.clone(),
1006                path: path.segments.clone(),
1007                value: match definition {
1008                    DataDefinition::InstanceList { .. } => {
1009                        crate::planning::execution_plan::show_instance_list_value(declaring, local)
1010                    }
1011                    _ => display.and_then(|d| {
1012                        d.value.as_ref().map(|bound| {
1013                            crate::planning::execution_plan::show_bound_result_value(
1014                                bound,
1015                                &lemma_type,
1016                                &input_key,
1017                                crate::planning::execution_plan::ShowBoundRole::Value,
1018                            )
1019                        })
1020                    }),
1021                },
1022                suggestion: display.and_then(|d| {
1023                    d.suggestion.as_ref().map(|bound| {
1024                        crate::planning::execution_plan::show_bound_result_value(
1025                            bound,
1026                            &lemma_type,
1027                            &input_key,
1028                            crate::planning::execution_plan::ShowBoundRole::Suggestion,
1029                        )
1030                    })
1031                }),
1032                needed_by_rules: used_by,
1033                list_writes: match definition {
1034                    DataDefinition::InstanceList { .. } => {
1035                        crate::planning::execution_plan::show_list_writes(declaring, local)
1036                    }
1037                    _ => None,
1038                },
1039            },
1040        ))
1041    }
1042
1043    /// Formatted canonical Lemma source for a repository or one spec slice.
1044    ///
1045    /// When `spec` is `None`, returns all specs in the repository sorted by name/effective.
1046    /// When `spec` is `Some`, `effective` selects the temporal slice (default: now).
1047    pub fn source(
1048        &self,
1049        repository: Option<&str>,
1050        spec: Option<&str>,
1051        effective: Option<&DateTimeValue>,
1052    ) -> Result<String, Error> {
1053        match spec {
1054            None => self.format_repository_source(repository),
1055            Some(spec_name) => {
1056                let effective_dt = self.effective_or_now(effective);
1057                let resolved_spec = self.get_spec(spec_name, repository, Some(&effective_dt))?;
1058                Ok(crate::formatting::format_spec_refs(&[resolved_spec]))
1059            }
1060        }
1061    }
1062
1063    /// Evaluate a spec.
1064    pub fn evaluate(
1065        &self,
1066        repository: Option<&str>,
1067        spec: &str,
1068        effective: Option<&DateTimeValue>,
1069        data: IndexMap<String, EvaluateDataValue>,
1070        rules: Option<&[String]>,
1071        explain: bool,
1072    ) -> Result<Response, Error> {
1073        let effective = self.effective_or_now(effective);
1074        let plan = self.plan(repository, spec, Some(&effective))?;
1075
1076        let response_rules = plan.validated_response_rule_paths(rules)?;
1077        let evaluate_data = EvaluateData::resolve(plan, data, &self.limits)?;
1078        let now_semantic = crate::planning::semantics::date_time_to_semantic(&effective);
1079        let now_literal = crate::planning::semantics::LiteralValue::date(now_semantic);
1080        let evaluator = Evaluator;
1081        let mut response =
1082            evaluator.evaluate(plan, &evaluate_data, now_literal, response_rules, explain);
1083
1084        response.spec_effective_from = plan.effective_from.clone();
1085        response.spec_effective_to = plan.effective_to.clone();
1086
1087        Ok(response)
1088    }
1089
1090    /// Deprecated alias of [`Engine::evaluate`].
1091    #[deprecated(note = "use evaluate")]
1092    pub fn run(
1093        &self,
1094        repository: Option<&str>,
1095        spec: &str,
1096        effective: Option<&DateTimeValue>,
1097        data: IndexMap<String, EvaluateDataValue>,
1098        rules: Option<&[String]>,
1099        explain: bool,
1100    ) -> Result<Response, Error> {
1101        self.evaluate(repository, spec, effective, data, rules, explain)
1102    }
1103
1104    fn format_repository_source(&self, repository: Option<&str>) -> Result<String, Error> {
1105        let repo_arc = self.resolve_repository(repository)?;
1106        let mut all_specs: Vec<&LemmaSpec> = self
1107            .context
1108            .spec_sets_for(&repo_arc)
1109            .flat_map(|ss| ss.iter_specs())
1110            .collect();
1111        all_specs.sort_by(|a, b| {
1112            a.name
1113                .cmp(&b.name)
1114                .then_with(|| a.effective_from.cmp(&b.effective_from))
1115        });
1116        let body = crate::formatting::format_spec_refs(&all_specs);
1117        let mut source_text = String::new();
1118        if let Some(name) = repo_arc.name.as_deref() {
1119            source_text.push_str("repo ");
1120            source_text.push_str(name);
1121            source_text.push_str("\n\n");
1122        }
1123        source_text.push_str(&body);
1124        Ok(source_text)
1125    }
1126
1127    fn resolve_repository(&self, repository: Option<&str>) -> Result<Arc<LemmaRepository>, Error> {
1128        match repository {
1129            None => Ok(self.context.workspace()),
1130            Some(qualifier) => {
1131                let q = qualifier.trim();
1132                if q.is_empty() {
1133                    return Err(Error::request(
1134                        "Repository qualifier cannot be empty",
1135                        None::<String>,
1136                    ));
1137                }
1138                self.context.find_repository(q).ok_or_else(|| {
1139                    Error::request_not_found(
1140                        format!("Repository '{qualifier}' not loaded"),
1141                        Some(format!(
1142                            "List repositories with `{}` after loading your workspace",
1143                            "lemma specs"
1144                        )),
1145                    )
1146                })
1147            }
1148        }
1149    }
1150
1151    fn spec_not_found_in_repository_error(
1152        &self,
1153        repository: &LemmaRepository,
1154        spec_name: &str,
1155        effective: &DateTimeValue,
1156    ) -> Error {
1157        let message = match &repository.name {
1158            Some(n) => {
1159                format!("Spec '{spec_name}' not found in repository {n} at effective {effective}")
1160            }
1161            None => format!("Spec '{spec_name}' not found at effective {effective}"),
1162        };
1163        Error::request_not_found(message, Some("Try `lemma specs`"))
1164    }
1165
1166    fn repository_for_lookup(
1167        &self,
1168        repository: Option<&str>,
1169    ) -> Result<Arc<LemmaRepository>, Error> {
1170        match repository {
1171            Some(q) => self.context.find_repository(q).ok_or_else(|| {
1172                Error::request_not_found(
1173                    format!("Repository '{q}' not loaded"),
1174                    Some("List repositories with `lemma specs` after loading your workspace"),
1175                )
1176            }),
1177            None => Ok(self.context.workspace()),
1178        }
1179    }
1180
1181    /// Effective datetime for a request: `explicit` or now.
1182    #[must_use]
1183    fn effective_or_now(&self, effective: Option<&DateTimeValue>) -> DateTimeValue {
1184        effective.cloned().unwrap_or_else(DateTimeValue::now)
1185    }
1186
1187    fn reserved_stdlib_error(source: Option<crate::parsing::source::Source>) -> Error {
1188        Error::validation(
1189            format!(
1190                "Repository '{EMBEDDED_STDLIB_REPOSITORY}' is reserved for the embedded standard library and cannot be loaded via load; use @owner/repo qualifiers (e.g. '@iso/countries'), not the reserved 'lemma' repository"
1191            ),
1192            source,
1193            Some(
1194                "Load registry dependencies with @owner/repo qualifiers, not the reserved 'lemma' stdlib repository"
1195                    .to_string(),
1196            ),
1197        )
1198    }
1199
1200    fn resource_limit_errors(
1201        name: &str,
1202        limit: impl ToString,
1203        actual: impl ToString,
1204        hint: &str,
1205        sources: IndexMap<SourceType, String>,
1206    ) -> Errors {
1207        Errors {
1208            errors: vec![Error::resource_limit_exceeded(
1209                name,
1210                limit.to_string(),
1211                actual.to_string(),
1212                hint,
1213                None::<crate::parsing::source::Source>,
1214                None,
1215                None,
1216            )],
1217            sources: sources.into_iter().collect(),
1218        }
1219    }
1220
1221    /// Apply removes then loads/replaces in one planning pass. Rolls back the whole batch on failure.
1222    ///
1223    /// Load sources are order-preserving so multi-source parse errors are reported in
1224    /// submission order rather than scrambled by hash iteration.
1225    fn apply(&mut self, mutations: Vec<Mutation>, embedded_stdlib: bool) -> Result<(), Errors> {
1226        let mut sources: IndexMap<SourceType, String> = IndexMap::new();
1227        let mut to_remove: Vec<(Arc<LemmaRepository>, String, EffectiveDate)> = Vec::new();
1228        let mut replace: Option<(Option<String>, SourceType, String)> = None;
1229        let mut saw_load = false;
1230        let mut saw_remove = false;
1231
1232        for mutation in mutations {
1233            match mutation {
1234                Mutation::Remove {
1235                    repository,
1236                    spec,
1237                    effective_from,
1238                } => {
1239                    let repo_ref = repository.as_deref();
1240                    let repository_arc = self.resolve_repository(repo_ref).unwrap_or_else(|e| {
1241                        panic!(
1242                            "BUG: Mutation::Remove repository must resolve after public remove validated it: {e}"
1243                        )
1244                    });
1245                    let spec_to_remove = self
1246                        .context
1247                        .spec_set(&repository_arc, &spec)
1248                        .and_then(|ss| ss.get_exact(effective_from.as_ref()))
1249                        .unwrap_or_else(|| {
1250                            panic!(
1251                                "BUG: Mutation::Remove target '{spec}' must exist after public remove validated it"
1252                            )
1253                        });
1254                    saw_remove = true;
1255                    to_remove.push((
1256                        Arc::clone(&repository_arc),
1257                        spec_to_remove.name.clone(),
1258                        spec_to_remove.effective_from.clone(),
1259                    ));
1260                }
1261                Mutation::Load { source_type, code } => {
1262                    saw_load = true;
1263                    if replace.is_some() {
1264                        panic!("BUG: Load and Replace in one apply");
1265                    }
1266                    if sources.insert(source_type.clone(), code).is_some() {
1267                        return Err(Errors {
1268                            errors: vec![Error::request(
1269                                format!("Duplicate source key: {source_type}"),
1270                                None::<String>,
1271                            )],
1272                            sources: sources.into_iter().collect(),
1273                        });
1274                    }
1275                }
1276                Mutation::Replace {
1277                    repository,
1278                    source_type,
1279                    code,
1280                } => {
1281                    if saw_load || !sources.is_empty() {
1282                        panic!("BUG: Load and Replace in one apply");
1283                    }
1284                    if replace.is_some() {
1285                        panic!("BUG: multiple Replace mutations in one apply");
1286                    }
1287                    replace = Some((repository, source_type, code));
1288                }
1289            }
1290        }
1291
1292        if saw_remove && (saw_load || replace.is_some()) {
1293            panic!("BUG: Remove mixed with Load or Replace in one apply");
1294        }
1295
1296        if let Some((repo_constraint, source_type, code)) = replace {
1297            return self.apply_replace(
1298                repo_constraint.as_deref(),
1299                source_type,
1300                code,
1301                embedded_stdlib,
1302            );
1303        }
1304
1305        for st in sources.keys() {
1306            if let Err(e) = Self::validate_source_type_key(st, embedded_stdlib) {
1307                return Err(Errors {
1308                    errors: vec![e],
1309                    sources: sources.into_iter().collect(),
1310                });
1311            }
1312        }
1313        self.check_batch_limits(&sources, embedded_stdlib)?;
1314
1315        let parse_limits = if embedded_stdlib {
1316            &ResourceLimits::default()
1317        } else {
1318            &self.limits
1319        };
1320        let mut staged: Vec<StagedSpec> = Vec::new();
1321        let mut errors: Vec<Error> = Vec::new();
1322
1323        for (source_id, code) in &sources {
1324            match self.stage_parsed_source(source_id, code, parse_limits, embedded_stdlib) {
1325                Ok(chunk) => staged.extend(chunk),
1326                Err(es) => errors.extend(es),
1327            }
1328        }
1329
1330        if !errors.is_empty() {
1331            return Err(Errors {
1332                errors,
1333                sources: sources.into_iter().collect(),
1334            });
1335        }
1336
1337        self.commit_staged(to_remove, staged, sources.into_iter().collect())
1338    }
1339
1340    fn validate_source_type_key(
1341        source_type: &SourceType,
1342        embedded_stdlib: bool,
1343    ) -> Result<(), Error> {
1344        match source_type {
1345            SourceType::Path(p) if p.as_os_str().to_string_lossy().trim().is_empty() => Err(
1346                Error::request("Source path must be non-empty", None::<String>),
1347            ),
1348            SourceType::Dependency(id) if id.is_empty() => Err(Error::request(
1349                "Dependency source identifier must be non-empty",
1350                None::<String>,
1351            )),
1352            SourceType::Dependency(id) if !embedded_stdlib && id == EMBEDDED_STDLIB_REPOSITORY => {
1353                Err(Self::reserved_stdlib_error(None))
1354            }
1355            _ => Ok(()),
1356        }
1357    }
1358
1359    fn check_batch_limits(
1360        &self,
1361        sources: &IndexMap<SourceType, String>,
1362        embedded_stdlib: bool,
1363    ) -> Result<(), Errors> {
1364        if embedded_stdlib || sources.is_empty() {
1365            return Ok(());
1366        }
1367        let limits = &self.limits;
1368        if sources.len() > limits.max_sources {
1369            return Err(Self::resource_limit_errors(
1370                "max_sources",
1371                limits.max_sources,
1372                sources.len(),
1373                "Reduce the number of paths or sources in one load",
1374                sources.clone(),
1375            ));
1376        }
1377        let total_loaded_bytes: usize = sources.values().map(|s| s.len()).sum();
1378        if total_loaded_bytes > limits.max_loaded_bytes {
1379            return Err(Self::resource_limit_errors(
1380                "max_loaded_bytes",
1381                limits.max_loaded_bytes,
1382                total_loaded_bytes,
1383                "Load fewer or smaller sources",
1384                sources.clone(),
1385            ));
1386        }
1387        if let Some(code) = sources
1388            .values()
1389            .find(|code| code.len() > limits.max_source_size_bytes)
1390        {
1391            return Err(Self::resource_limit_errors(
1392                "max_source_size_bytes",
1393                limits.max_source_size_bytes,
1394                code.len(),
1395                "Use a smaller source text or increase limit",
1396                sources.clone(),
1397            ));
1398        }
1399        Ok(())
1400    }
1401
1402    fn stage_parsed_source(
1403        &self,
1404        source_id: &SourceType,
1405        code: &str,
1406        parse_limits: &ResourceLimits,
1407        embedded_stdlib: bool,
1408    ) -> Result<Vec<StagedSpec>, Vec<Error>> {
1409        let dependency = match source_id {
1410            SourceType::Dependency(id) => Some(id.as_str()),
1411            _ => None,
1412        };
1413        let result = parse(code, source_id.clone(), parse_limits).map_err(|e| vec![e])?;
1414        if result.repositories.is_empty() {
1415            return Ok(Vec::new());
1416        }
1417
1418        let mut staged = Vec::new();
1419        let mut errors = Vec::new();
1420        for (parsed_repo, specs) in result.repositories {
1421            let repository_arc = if let Some(dep_id) = dependency {
1422                let repo_name = parsed_repo
1423                    .name
1424                    .clone()
1425                    .or_else(|| Some(dep_id.to_string()));
1426                Arc::new(
1427                    LemmaRepository::new(repo_name)
1428                        .with_dependency(dep_id)
1429                        .with_start_line(parsed_repo.start_line),
1430                )
1431            } else {
1432                parsed_repo
1433            };
1434            if !embedded_stdlib
1435                && repository_arc.name.as_deref() == Some(EMBEDDED_STDLIB_REPOSITORY)
1436            {
1437                let source = crate::parsing::source::Source::new(
1438                    source_id.clone(),
1439                    crate::parsing::ast::Span {
1440                        start: 0,
1441                        end: 0,
1442                        line: repository_arc.start_line,
1443                        col: 0,
1444                    },
1445                );
1446                errors.push(Self::reserved_stdlib_error(Some(source)));
1447                continue;
1448            }
1449            for spec in specs {
1450                staged.push((source_id.clone(), Arc::clone(&repository_arc), spec));
1451            }
1452        }
1453        if !errors.is_empty() {
1454            return Err(errors);
1455        }
1456        Ok(staged)
1457    }
1458
1459    fn apply_replace(
1460        &mut self,
1461        repository_constraint: Option<&str>,
1462        source_type: SourceType,
1463        code: String,
1464        embedded_stdlib: bool,
1465    ) -> Result<(), Errors> {
1466        let mut sources: IndexMap<SourceType, String> = IndexMap::new();
1467        sources.insert(source_type.clone(), code);
1468
1469        if let Err(e) = Self::validate_source_type_key(&source_type, embedded_stdlib) {
1470            return Err(Errors {
1471                errors: vec![e],
1472                sources: sources.into_iter().collect(),
1473            });
1474        }
1475
1476        self.check_batch_limits(&sources, embedded_stdlib)?;
1477
1478        let parse_limits = if embedded_stdlib {
1479            &ResourceLimits::default()
1480        } else {
1481            &self.limits
1482        };
1483
1484        let staged = match self.stage_parsed_source(
1485            &source_type,
1486            &sources[&source_type],
1487            parse_limits,
1488            embedded_stdlib,
1489        ) {
1490            Ok(s) => s,
1491            Err(errors) => {
1492                return Err(Errors {
1493                    errors,
1494                    sources: sources.into_iter().collect(),
1495                });
1496            }
1497        };
1498
1499        let prune = matches!(source_type, SourceType::Path(_) | SourceType::Dependency(_));
1500        if staged.is_empty() && !prune {
1501            return Err(Errors {
1502                errors: vec![Error::request(
1503                    "update requires at least one spec",
1504                    None::<String>,
1505                )],
1506                sources: sources.into_iter().collect(),
1507            });
1508        }
1509
1510        if let Some(required) = repository_constraint {
1511            let required_canonical =
1512                crate::parsing::ast::ascii_lowercase_logical_name(required.to_string());
1513            for (_, repository_arc, _) in &staged {
1514                if repository_arc.name.as_deref() != Some(required_canonical.as_str()) {
1515                    return Err(Errors {
1516                        errors: vec![Error::request(
1517                            match repository_arc.name.as_deref() {
1518                                Some(name) => format!(
1519                                    "update repository '{required}' does not match staged repository '{name}'"
1520                                ),
1521                                None => format!(
1522                                    "update repository '{required}' does not match the default repository"
1523                                ),
1524                            },
1525                            None::<String>,
1526                        )],
1527                        sources: sources.into_iter().collect(),
1528                    });
1529                }
1530            }
1531        }
1532
1533        let mut staged_keys: std::collections::HashSet<(Option<String>, String, EffectiveDate)> =
1534            std::collections::HashSet::new();
1535        for (_, repository_arc, spec) in &staged {
1536            staged_keys.insert((
1537                repository_arc.name.clone(),
1538                spec.name.clone(),
1539                spec.effective_from.clone(),
1540            ));
1541        }
1542
1543        let mut to_remove: Vec<(Arc<LemmaRepository>, String, EffectiveDate)> = Vec::new();
1544        for (repository, by_name) in self.context.repositories() {
1545            for spec_set in by_name.values() {
1546                for spec in spec_set.iter_specs() {
1547                    if spec.source_type.as_ref() != Some(&source_type) {
1548                        continue;
1549                    }
1550                    let key = (
1551                        repository.name.clone(),
1552                        spec.name.clone(),
1553                        spec.effective_from.clone(),
1554                    );
1555                    if prune || staged_keys.contains(&key) {
1556                        to_remove.push((
1557                            Arc::clone(repository),
1558                            spec.name.clone(),
1559                            spec.effective_from.clone(),
1560                        ));
1561                    }
1562                }
1563            }
1564        }
1565
1566        let staged_for_commit: Vec<StagedSpec> = staged
1567            .into_iter()
1568            .map(|(_, repo, spec)| (source_type.clone(), repo, spec))
1569            .collect();
1570
1571        self.commit_staged(to_remove, staged_for_commit, sources.into_iter().collect())
1572    }
1573
1574    fn commit_staged(
1575        &mut self,
1576        to_remove: Vec<(Arc<LemmaRepository>, String, EffectiveDate)>,
1577        staged: Vec<StagedSpec>,
1578        sources: HashMap<SourceType, String>,
1579    ) -> Result<(), Errors> {
1580        let mut removed: Vec<RemovedSpec> = Vec::new();
1581        for (repository, name, effective_from) in to_remove {
1582            let spec = self
1583                .context
1584                .take_spec(&repository, &name, effective_from.as_ref())
1585                .expect("BUG: a spec to remove must be live in context");
1586            removed.push(RemovedSpec { repository, spec });
1587        }
1588
1589        let mut inserted: Vec<(Arc<LemmaRepository>, String, EffectiveDate)> = Vec::new();
1590        let mut errors: Vec<Error> = Vec::new();
1591        for (_, repository_arc, spec) in staged {
1592            let name = spec.name.clone();
1593            let effective_from = spec.effective_from.clone();
1594            let replaced = removed
1595                .iter()
1596                .find(|replaced| {
1597                    replaced.repository == repository_arc
1598                        && replaced.spec.name == name
1599                        && replaced.spec.effective_from == effective_from
1600                })
1601                .map(|replaced| Arc::clone(&replaced.spec));
1602            match self
1603                .context
1604                .insert_spec_replacing(Arc::clone(&repository_arc), spec, replaced)
1605            {
1606                Ok(()) => inserted.push((repository_arc, name, effective_from)),
1607                Err(es) => errors.extend(es),
1608            }
1609        }
1610        if !errors.is_empty() {
1611            self.rollback_apply(&inserted, removed);
1612            return Err(Errors { errors, sources });
1613        }
1614
1615        let result = crate::planning::plan(&self.context, &self.limits, &self.plans);
1616        if !result.errors.is_empty() {
1617            self.rollback_apply(&inserted, removed);
1618            return Err(Errors {
1619                errors: result.errors,
1620                sources,
1621            });
1622        }
1623
1624        self.plans = result.plans;
1625        self.context.remove_empty_repositories();
1626        Ok(())
1627    }
1628
1629    fn rollback_apply(
1630        &mut self,
1631        inserted: &[(Arc<LemmaRepository>, String, EffectiveDate)],
1632        removed: Vec<RemovedSpec>,
1633    ) {
1634        for (repo, inserted_name, inserted_effective) in inserted.iter().rev() {
1635            if !self.context.remove_spec_by_identity(
1636                repo,
1637                inserted_name,
1638                inserted_effective.as_ref(),
1639            ) {
1640                panic!("BUG: inserted spec must be removable on rollback");
1641            }
1642        }
1643        for removed_spec in removed.into_iter().rev() {
1644            let RemovedSpec { repository, spec } = removed_spec;
1645            let name = spec.name.clone();
1646            let effective_from = spec.effective_from.clone();
1647            self.context
1648                .insert_spec_replacing_owned(Arc::clone(&repository), Arc::clone(&spec))
1649                .expect("BUG: restore removed spec for rollback");
1650            let spec_set = self
1651                .context
1652                .spec_set(&repository, &name)
1653                .expect("BUG: restored spec set must be live after rollback");
1654            let restored = spec_set.spec_arc(
1655                spec_set
1656                    .get_exact(effective_from.as_ref())
1657                    .expect("BUG: restored spec must be live after rollback"),
1658            );
1659            assert!(
1660                Arc::ptr_eq(restored, &spec),
1661                "BUG: rollback of spec '{name}' must restore its own Arc"
1662            );
1663        }
1664    }
1665
1666    /// Active [`LemmaSpec`] slice for `name` at the resolved effective instant in `repository`.
1667    ///
1668    /// When `repository` is `None`, uses the default unnamed repository. When `effective` is `None`, uses now.
1669    pub(crate) fn get_spec(
1670        &self,
1671        name: &str,
1672        repository: Option<&str>,
1673        effective: Option<&DateTimeValue>,
1674    ) -> Result<&LemmaSpec, Error> {
1675        let effective_dt = self.effective_or_now(effective);
1676        let instant = EffectiveDate::DateTimeValue(effective_dt.clone());
1677        let repository_arc = match repository {
1678            Some(q) => self.context.find_repository(q).ok_or_else(|| {
1679                Error::request_not_found(
1680                    format!("Repository '{q}' not loaded"),
1681                    Some("List repositories with `lemma specs` after loading your workspace"),
1682                )
1683            })?,
1684            None => self.context.workspace(),
1685        };
1686        let spec_set = self
1687            .context
1688            .spec_set(&repository_arc, name)
1689            .ok_or_else(|| {
1690                self.spec_not_found_in_repository_error(&repository_arc, name, &effective_dt)
1691            })?;
1692        spec_set.spec_at(&instant).ok_or_else(|| {
1693            self.spec_not_found_in_repository_error(&repository_arc, name, &effective_dt)
1694        })
1695    }
1696}
1697#[cfg(test)]
1698mod tests {
1699    use super::*;
1700
1701    fn date(year: i32, month: u32, day: u32) -> DateTimeValue {
1702        DateTimeValue {
1703            year,
1704            month,
1705            day,
1706            hour: 0,
1707            minute: 0,
1708            second: 0,
1709            microsecond: 0,
1710            timezone: None,
1711            granularity: crate::literals::DateGranularity::Full,
1712        }
1713    }
1714
1715    /// Each source parses into its own `LemmaRepository` `Arc`. A spec set must hold the
1716    /// context's `Arc` for its repository, so one repository is one allocation however
1717    /// many sources and replans contribute specs to it.
1718    #[test]
1719    fn every_spec_set_shares_its_repository_arc_with_the_context() {
1720        let path = |name: &str| SourceType::Path(Arc::new(std::path::PathBuf::from(name)));
1721        let mut engine = Engine::new();
1722        engine
1723            .load([
1724                (path("a.lemma"), "spec a\ndata x: 1\n"),
1725                (path("b.lemma"), "spec b\nuses a\nrule y: a.x\n"),
1726                (path("c.lemma"), "repo shared\nspec c\ndata z: 1\n"),
1727                (path("d.lemma"), "repo shared\nspec d\ndata w: 1\n"),
1728            ])
1729            .expect("sources load");
1730        engine
1731            .update(None, "spec a\ndata x: 1\n".to_string(), path("a.lemma"))
1732            .expect("unchanged a applies");
1733        engine
1734            .update(
1735                None,
1736                "spec b\nuses a\nrule y: a.missing\n".to_string(),
1737                path("b.lemma"),
1738            )
1739            .expect_err("b reading a missing rule fails to plan");
1740
1741        let mut unshared = Vec::new();
1742        for (repository, by_name) in engine.context.repositories() {
1743            for spec_set in by_name.values() {
1744                if !Arc::ptr_eq(repository, &spec_set.repository) {
1745                    unshared.push(format!("{:?} {}", repository.name, spec_set.name));
1746                }
1747            }
1748        }
1749        assert!(
1750            unshared.is_empty(),
1751            "spec sets hold their own repository Arc: {}",
1752            unshared.join(", ")
1753        );
1754    }
1755
1756    /// A repository whose last spec is removed no longer exists, so its provenance must
1757    /// not outlive it: a local source may then declare a repository of the same name.
1758    #[test]
1759    fn a_repository_emptied_of_dependency_specs_can_be_declared_locally() {
1760        let mut engine = Engine::new();
1761        engine
1762            .load([(
1763                SourceType::Dependency("shared".to_string()),
1764                "spec a\ndata v: 1\n",
1765            )])
1766            .expect("dependency loads");
1767        engine
1768            .remove(Some("shared"), "a", None)
1769            .expect("dependency spec removes");
1770        engine
1771            .load([(
1772                SourceType::Path(Arc::new(std::path::PathBuf::from("local.lemma"))),
1773                "repo shared\nspec b\ndata w: 1\n",
1774            )])
1775            .expect("a local repository named like a removed dependency repository loads");
1776    }
1777
1778    /// Removing the last spec of a named repository removes the repository from the
1779    /// listing; the default repository is always listed.
1780    #[test]
1781    fn an_emptied_repository_is_not_listed() {
1782        let path = |name: &str| SourceType::Path(Arc::new(std::path::PathBuf::from(name)));
1783        let mut engine = Engine::new();
1784        engine
1785            .load([
1786                (path("named.lemma"), "repo shared\nspec c\ndata z: 1\n"),
1787                (path("default.lemma"), "spec d\ndata w: 1\n"),
1788            ])
1789            .expect("sources load");
1790        engine
1791            .remove(Some("shared"), "c", None)
1792            .expect("named spec removes");
1793        engine
1794            .remove(None, "d", None)
1795            .expect("default spec removes");
1796
1797        let listed: Vec<Option<String>> = engine
1798            .specs()
1799            .into_iter()
1800            .map(|repository| repository.repository)
1801            .collect();
1802        assert!(
1803            !listed.contains(&Some("shared".to_string())),
1804            "emptied repository still listed: {listed:?}"
1805        );
1806        assert!(
1807            listed.contains(&None),
1808            "default repository must stay listed: {listed:?}"
1809        );
1810    }
1811
1812    /// Re-parsing the only file of a repository, or failing a batch that replaces it,
1813    /// leaves the repository where it was in the listing.
1814    #[test]
1815    fn replacing_every_spec_of_a_repository_keeps_its_position() {
1816        let path = |name: &str| SourceType::Path(Arc::new(std::path::PathBuf::from(name)));
1817        let mut engine = Engine::new();
1818        engine
1819            .load([
1820                (path("north.lemma"), "repo north\nspec a\ndata x: 1\n"),
1821                (path("south.lemma"), "repo south\nspec b\ndata y: 1\n"),
1822            ])
1823            .expect("sources load");
1824        let order = |engine: &Engine| -> Vec<Option<String>> {
1825            engine
1826                .specs()
1827                .into_iter()
1828                .map(|repository| repository.repository)
1829                .collect()
1830        };
1831        let loaded = order(&engine);
1832
1833        engine
1834            .update(
1835                Some("north"),
1836                "repo north\nspec a\ndata x: 1\n".to_string(),
1837                path("north.lemma"),
1838            )
1839            .expect("unchanged north applies");
1840        assert_eq!(order(&engine), loaded, "after an unchanged re-parse");
1841
1842        engine
1843            .update(
1844                Some("north"),
1845                "repo north\nspec a\nrule r: missing\n".to_string(),
1846                path("north.lemma"),
1847            )
1848            .expect_err("a rule reading missing data fails to plan");
1849        assert_eq!(order(&engine), loaded, "after a failed batch");
1850    }
1851
1852    #[test]
1853    fn format_repositories_prints_each_temporal_version() {
1854        let text = format_repositories(
1855            &[
1856                Repository {
1857                    repository: None,
1858                    from_dependency: false,
1859                    specs: vec![
1860                        SpecVersion {
1861                            name: "legacy".into(),
1862                            effective_from: None,
1863                            effective_to: Some(date(2026, 1, 1)),
1864                            dependencies: Vec::new(),
1865                        },
1866                        SpecVersion {
1867                            name: "taxes".into(),
1868                            effective_from: None,
1869                            effective_to: None,
1870                            dependencies: Vec::new(),
1871                        },
1872                        SpecVersion {
1873                            name: "pricing".into(),
1874                            effective_from: Some(date(2026, 1, 1)),
1875                            effective_to: None,
1876                            dependencies: Vec::new(),
1877                        },
1878                        SpecVersion {
1879                            name: "pricing".into(),
1880                            effective_from: Some(date(2025, 1, 1)),
1881                            effective_to: Some(date(2026, 1, 1)),
1882                            dependencies: Vec::new(),
1883                        },
1884                    ],
1885                },
1886                Repository {
1887                    repository: Some("@iso/countries".into()),
1888                    from_dependency: true,
1889                    specs: vec![SpecVersion {
1890                        name: "alpha2".into(),
1891                        effective_from: Some(date(2011, 8, 9)),
1892                        effective_to: None,
1893                        dependencies: Vec::new(),
1894                    }],
1895                },
1896            ],
1897            true,
1898        );
1899        assert_eq!(
1900            text,
1901            "legacy ...2026-01-01\npricing 2025-01-01...2026-01-01\npricing 2026-01-01\ntaxes\n\n@iso/countries\n  alpha2 2011-08-09\n"
1902        );
1903    }
1904
1905    #[test]
1906    fn spec_version_display_omits_arrow_without_an_end() {
1907        assert_eq!(
1908            SpecVersion {
1909                name: "pricing".into(),
1910                effective_from: Some(date(2025, 1, 1)),
1911                effective_to: Some(date(2026, 1, 1)),
1912                dependencies: Vec::new(),
1913            }
1914            .to_string(),
1915            "pricing 2025-01-01...2026-01-01"
1916        );
1917        assert_eq!(
1918            SpecVersion {
1919                name: "pricing".into(),
1920                effective_from: Some(date(2026, 1, 1)),
1921                effective_to: None,
1922                dependencies: Vec::new(),
1923            }
1924            .to_string(),
1925            "pricing 2026-01-01"
1926        );
1927        assert_eq!(
1928            SpecVersion {
1929                name: "pricing".into(),
1930                effective_from: None,
1931                effective_to: Some(date(2026, 1, 1)),
1932                dependencies: Vec::new(),
1933            }
1934            .to_string(),
1935            "pricing ...2026-01-01"
1936        );
1937        assert_eq!(
1938            SpecVersion {
1939                name: "taxes".into(),
1940                effective_from: None,
1941                effective_to: None,
1942                dependencies: Vec::new(),
1943            }
1944            .to_string(),
1945            "taxes"
1946        );
1947    }
1948
1949    #[test]
1950    fn format_local_specs_prints_uses_and_omits_dependency_repositories() {
1951        let text = format_repositories(
1952            &[
1953                Repository {
1954                    repository: None,
1955                    from_dependency: false,
1956                    specs: vec![SpecVersion {
1957                        name: "outer".into(),
1958                        effective_from: None,
1959                        effective_to: None,
1960                        dependencies: vec![
1961                            SpecDependency {
1962                                repository: None,
1963                                name: "inner".into(),
1964                                effective: None,
1965                            },
1966                            SpecDependency {
1967                                repository: Some("lemma".into()),
1968                                name: "units".into(),
1969                                effective: None,
1970                            },
1971                        ],
1972                    }],
1973                },
1974                Repository {
1975                    repository: Some("lemma".into()),
1976                    from_dependency: true,
1977                    specs: vec![SpecVersion {
1978                        name: "units".into(),
1979                        effective_from: None,
1980                        effective_to: None,
1981                        dependencies: Vec::new(),
1982                    }],
1983                },
1984            ],
1985            false,
1986        );
1987        assert_eq!(text, "outer\n  inner\n  lemma units\n");
1988    }
1989
1990    #[test]
1991    fn specs_rows_carry_uses_targets() {
1992        let mut engine = Engine::new();
1993        engine
1994            .load([(
1995                SourceType::Path(Arc::new(std::path::PathBuf::from("main.lemma"))),
1996                r#"
1997spec inner 2024-01-01
1998data x: 1
1999
2000spec outer
2001uses inner 2024-01-01
2002uses u: lemma units
2003rule r: inner.x
2004"#
2005                .to_string(),
2006            )])
2007            .expect("load");
2008        let workspace = engine
2009            .specs()
2010            .into_iter()
2011            .find(|repo| repo.repository.is_none())
2012            .expect("workspace");
2013        let outer = workspace
2014            .specs
2015            .iter()
2016            .find(|version| version.name == "outer")
2017            .expect("outer");
2018        assert_eq!(
2019            outer.dependencies,
2020            vec![
2021                SpecDependency {
2022                    repository: None,
2023                    name: "inner".into(),
2024                    effective: Some(date(2024, 1, 1)),
2025                },
2026                SpecDependency {
2027                    repository: Some("lemma".into()),
2028                    name: "units".into(),
2029                    effective: None,
2030                },
2031            ]
2032        );
2033        assert!(engine
2034            .specs()
2035            .iter()
2036            .any(|repo| repo.repository.as_deref() == Some("lemma") && repo.from_dependency));
2037    }
2038
2039    fn make_spec_with_range(name: &str, effective_from: Option<DateTimeValue>) -> LemmaSpec {
2040        let mut spec = LemmaSpec::new(name.to_string());
2041        spec.effective_from = crate::parsing::ast::EffectiveDate::from_option(effective_from);
2042        spec
2043    }
2044
2045    /// Spec-set temporal order is (name, effective_from) ascending.
2046    /// Same-name specs appear in temporal order; definition order in the source is irrelevant.
2047    #[test]
2048    fn list_order_is_name_then_effective_from_ascending() {
2049        let mut ctx = Context::new();
2050        let repository = ctx.workspace();
2051        let s_2026 = make_spec_with_range("mortgage", Some(date(2026, 1, 1)));
2052        let s_2025 = make_spec_with_range("mortgage", Some(date(2025, 1, 1)));
2053        ctx.insert_spec(Arc::clone(&repository), s_2026).unwrap();
2054        ctx.insert_spec(Arc::clone(&repository), s_2025).unwrap();
2055        let listed: Vec<_> = ctx
2056            .spec_set(&repository, "mortgage")
2057            .expect("mortgage set")
2058            .iter_specs()
2059            .collect();
2060        assert_eq!(listed.len(), 2);
2061        assert_eq!(listed[0].effective_from(), Some(&date(2025, 1, 1)));
2062        assert_eq!(listed[1].effective_from(), Some(&date(2026, 1, 1)));
2063    }
2064
2065    #[test]
2066    fn get_spec_resolves_temporal_version_by_effective() {
2067        let mut engine = Engine::new();
2068        engine
2069            .load([(
2070                SourceType::Path(Arc::new(std::path::PathBuf::from("a.lemma"))),
2071                r#"
2072        spec pricing 2025-01-01
2073        data x: 1
2074        rule r: x
2075    "#
2076                .to_string(),
2077            )])
2078            .unwrap();
2079        engine
2080            .load([(
2081                SourceType::Path(Arc::new(std::path::PathBuf::from("b.lemma"))),
2082                r#"
2083        spec pricing 2025-06-01
2084        data x: 2
2085        rule r: x
2086    "#
2087                .to_string(),
2088            )])
2089            .unwrap();
2090
2091        let jan = DateTimeValue {
2092            year: 2025,
2093            month: 1,
2094            day: 15,
2095            hour: 0,
2096            minute: 0,
2097            second: 0,
2098            microsecond: 0,
2099            timezone: None,
2100            granularity: crate::literals::DateGranularity::Full,
2101        };
2102        let jul = DateTimeValue {
2103            year: 2025,
2104            month: 7,
2105            day: 1,
2106            hour: 0,
2107            minute: 0,
2108            second: 0,
2109            microsecond: 0,
2110            timezone: None,
2111            granularity: crate::literals::DateGranularity::Full,
2112        };
2113
2114        let v1 = DateTimeValue {
2115            year: 2025,
2116            month: 1,
2117            day: 1,
2118            hour: 0,
2119            minute: 0,
2120            second: 0,
2121            microsecond: 0,
2122            timezone: None,
2123            granularity: crate::literals::DateGranularity::Full,
2124        };
2125        let v2 = DateTimeValue {
2126            year: 2025,
2127            month: 6,
2128            day: 1,
2129            hour: 0,
2130            minute: 0,
2131            second: 0,
2132            microsecond: 0,
2133            timezone: None,
2134            granularity: crate::literals::DateGranularity::Full,
2135        };
2136
2137        let s_jan = engine
2138            .get_spec("pricing", None, Some(&jan))
2139            .expect("jan spec");
2140        let s_jul = engine
2141            .get_spec("pricing", None, Some(&jul))
2142            .expect("jul spec");
2143        assert_eq!(s_jan.effective_from(), Some(&v1));
2144        assert_eq!(s_jul.effective_from(), Some(&v2));
2145    }
2146
2147    /// Every temporal row for a workspace spec name exposes half-open
2148    /// `[effective_from, effective_to)` via [`LemmaSpecSet::iter_with_ranges`]. The latest row's
2149    /// `effective_to` is `None` (no successor); earlier rows' `effective_to`
2150    /// equals the next row's `effective_from`.
2151    #[test]
2152    fn list_returns_half_open_ranges_per_temporal_version() {
2153        let mut engine = Engine::new();
2154        engine
2155            .load([(
2156                SourceType::Path(Arc::new(std::path::PathBuf::from("a.lemma"))),
2157                r#"
2158        spec pricing 2025-01-01
2159        data x: 1
2160        rule r: x
2161    "#
2162                .to_string(),
2163            )])
2164            .unwrap();
2165        engine
2166            .load([(
2167                SourceType::Path(Arc::new(std::path::PathBuf::from("b.lemma"))),
2168                r#"
2169        spec pricing 2025-06-01
2170        data x: 2
2171        rule r: x
2172    "#
2173                .to_string(),
2174            )])
2175            .unwrap();
2176
2177        let january = date(2025, 1, 1);
2178        let june = date(2025, 6, 1);
2179
2180        let workspace = engine
2181            .specs()
2182            .into_iter()
2183            .find(|r| r.repository.is_none())
2184            .expect("workspace");
2185        let mut pricing_rows: Vec<_> = workspace
2186            .specs
2187            .iter()
2188            .filter(|ls| ls.name == "pricing")
2189            .map(|ls| (ls.effective_from.clone(), ls.effective_to.clone()))
2190            .collect();
2191        pricing_rows.sort_by(|a, b| match (&a.0, &b.0) {
2192            (Some(x), Some(y)) => x.cmp(y),
2193            (None, Some(_)) => std::cmp::Ordering::Less,
2194            (Some(_), None) => std::cmp::Ordering::Greater,
2195            (None, None) => std::cmp::Ordering::Equal,
2196        });
2197        assert_eq!(pricing_rows.len(), 2);
2198        assert_eq!(
2199            pricing_rows[0],
2200            (Some(january.clone()), Some(june.clone())),
2201            "earlier row ends at the next row's effective_from"
2202        );
2203        assert_eq!(
2204            pricing_rows[1],
2205            (Some(june.clone()), None),
2206            "latest row has no successor; effective_to is None"
2207        );
2208
2209        assert!(
2210            !engine
2211                .specs()
2212                .into_iter()
2213                .find(|r| r.repository.is_none())
2214                .expect("workspace")
2215                .specs
2216                .iter()
2217                .any(|ls| ls.name == "unknown"),
2218            "no rows for unknown spec"
2219        );
2220    }
2221
2222    /// `Engine::specs()` provides spec sets grouped by repository.
2223    /// Each spec version row exposes half-open `[effective_from, effective_to)` ranges.
2224    #[test]
2225    fn get_workspace_specs_with_half_open_ranges() {
2226        let mut engine = Engine::new();
2227        engine
2228            .load([(
2229                SourceType::Path(Arc::new(std::path::PathBuf::from("pricing_v1.lemma"))),
2230                r#"
2231        spec pricing 2025-01-01
2232        data x: 1
2233        rule r: x
2234    "#
2235                .to_string(),
2236            )])
2237            .unwrap();
2238        engine
2239            .load([(
2240                SourceType::Path(Arc::new(std::path::PathBuf::from("pricing_v2.lemma"))),
2241                r#"
2242        spec pricing 2026-01-01
2243        data x: 2
2244        rule r: x
2245    "#
2246                .to_string(),
2247            )])
2248            .unwrap();
2249        engine
2250            .load([(
2251                SourceType::Path(Arc::new(std::path::PathBuf::from("taxes.lemma"))),
2252                r#"
2253        spec taxes
2254        data rate: 0.21
2255        rule amount: rate
2256    "#
2257                .to_string(),
2258            )])
2259            .unwrap();
2260
2261        let workspace = engine
2262            .specs()
2263            .into_iter()
2264            .find(|r| r.repository.is_none())
2265            .expect("workspace");
2266        let unique_names: std::collections::BTreeSet<&str> =
2267            workspace.specs.iter().map(|ls| ls.name.as_str()).collect();
2268        assert_eq!(
2269            unique_names.len(),
2270            2,
2271            "two unique spec names: pricing and taxes"
2272        );
2273
2274        let pricing_rows: Vec<_> = workspace
2275            .specs
2276            .iter()
2277            .filter(|ls| ls.name == "pricing")
2278            .collect();
2279        assert_eq!(pricing_rows.len(), 2);
2280        assert_eq!(pricing_rows[0].effective_from, Some(date(2025, 1, 1)));
2281        assert_eq!(
2282            pricing_rows[0].effective_to,
2283            Some(date(2026, 1, 1)),
2284            "earlier pricing row ends at the next pricing row's effective_from"
2285        );
2286        assert_eq!(pricing_rows[1].effective_from, Some(date(2026, 1, 1)));
2287        assert_eq!(
2288            pricing_rows[1].effective_to, None,
2289            "latest pricing row has no successor; effective_to is None"
2290        );
2291
2292        let tax_rows: Vec<_> = workspace
2293            .specs
2294            .iter()
2295            .filter(|ls| ls.name == "taxes")
2296            .collect();
2297        assert_eq!(tax_rows.len(), 1);
2298        assert_eq!(
2299            tax_rows[0].effective_from, None,
2300            "unversioned spec has no declared effective_from"
2301        );
2302        assert_eq!(
2303            tax_rows[0].effective_to, None,
2304            "unversioned spec has no successor; effective_to is None"
2305        );
2306    }
2307
2308    #[test]
2309    fn test_evaluate_spec_all_rules() {
2310        let mut engine = Engine::new();
2311        engine
2312            .load([(
2313                SourceType::Path(Arc::new(std::path::PathBuf::from("test.lemma"))),
2314                r#"
2315        spec test
2316        data x: 10
2317        data y: 5
2318        rule added: x + y
2319        rule multiplied: x * y
2320    "#
2321                .to_string(),
2322            )])
2323            .unwrap();
2324
2325        let now = DateTimeValue::now();
2326        let response = engine
2327            .evaluate(None, "test", Some(&now), IndexMap::new(), None, false)
2328            .unwrap();
2329        assert_eq!(response.results.len(), 2);
2330
2331        let sum_result = response
2332            .results
2333            .values()
2334            .find(|r| r.rule.name == "added")
2335            .unwrap();
2336        assert_eq!(sum_result.result().expect("result").to_string(), "15");
2337
2338        let product_result = response
2339            .results
2340            .values()
2341            .find(|r| r.rule.name == "multiplied")
2342            .unwrap();
2343        assert_eq!(product_result.result().expect("result").to_string(), "50");
2344    }
2345
2346    #[test]
2347    fn test_evaluate_empty_data() {
2348        let mut engine = Engine::new();
2349        engine
2350            .load([(
2351                SourceType::Path(Arc::new(std::path::PathBuf::from("test.lemma"))),
2352                r#"
2353        spec test
2354        data price: 100
2355        rule total: price * 2
2356    "#
2357                .to_string(),
2358            )])
2359            .unwrap();
2360
2361        let now = DateTimeValue::now();
2362        let response = engine
2363            .evaluate(None, "test", Some(&now), IndexMap::new(), None, false)
2364            .unwrap();
2365        assert_eq!(response.results.len(), 1);
2366        assert_eq!(
2367            response
2368                .results
2369                .values()
2370                .next()
2371                .unwrap()
2372                .result()
2373                .expect("result"),
2374            "200"
2375        );
2376    }
2377
2378    #[test]
2379    fn test_evaluate_boolean_rule() {
2380        let mut engine = Engine::new();
2381        engine
2382            .load([(
2383                SourceType::Path(Arc::new(std::path::PathBuf::from("test.lemma"))),
2384                r#"
2385        spec test
2386        data age: 25
2387        rule is_adult: age >= 18
2388    "#
2389                .to_string(),
2390            )])
2391            .unwrap();
2392
2393        let now = DateTimeValue::now();
2394        let response = engine
2395            .evaluate(None, "test", Some(&now), IndexMap::new(), None, false)
2396            .unwrap();
2397        assert_eq!(
2398            response
2399                .results
2400                .values()
2401                .next()
2402                .unwrap()
2403                .result
2404                .as_ref()
2405                .unwrap()
2406                .boolean,
2407            Some(true)
2408        );
2409    }
2410
2411    #[test]
2412    fn test_evaluate_with_unless_clause() {
2413        let mut engine = Engine::new();
2414        engine
2415            .load([(
2416                SourceType::Path(Arc::new(std::path::PathBuf::from("test.lemma"))),
2417                r#"
2418        spec test
2419        data quantity: 15
2420        rule discount: 0
2421          unless quantity >= 10 then 10
2422    "#
2423                .to_string(),
2424            )])
2425            .unwrap();
2426
2427        let now = DateTimeValue::now();
2428        let response = engine
2429            .evaluate(None, "test", Some(&now), IndexMap::new(), None, false)
2430            .unwrap();
2431        assert_eq!(
2432            response
2433                .results
2434                .values()
2435                .next()
2436                .unwrap()
2437                .result()
2438                .expect("result"),
2439            "10"
2440        );
2441    }
2442
2443    #[test]
2444    fn test_spec_not_found() {
2445        let engine = Engine::new();
2446        let now = DateTimeValue::now();
2447        let result = engine.evaluate(
2448            None,
2449            "nonexistent",
2450            Some(&now),
2451            IndexMap::new(),
2452            None,
2453            false,
2454        );
2455        assert!(result.is_err());
2456        let msg = result.unwrap_err().to_string();
2457        assert!(
2458            msg.contains("not found") && msg.contains("nonexistent"),
2459            "missing spec must report attributed not-found, got: {msg}"
2460        );
2461    }
2462
2463    #[test]
2464    fn test_multiple_specs() {
2465        let mut engine = Engine::new();
2466        engine
2467            .load([(
2468                SourceType::Path(Arc::new(std::path::PathBuf::from("spec 1.lemma"))),
2469                r#"
2470        spec spec1
2471        data x: 10
2472        rule result: x * 2
2473    "#
2474                .to_string(),
2475            )])
2476            .unwrap();
2477
2478        engine
2479            .load([(
2480                SourceType::Path(Arc::new(std::path::PathBuf::from("spec 2.lemma"))),
2481                r#"
2482        spec spec2
2483        data y: 5
2484        rule result: y * 3
2485    "#
2486                .to_string(),
2487            )])
2488            .unwrap();
2489
2490        let now = DateTimeValue::now();
2491        let response1 = engine
2492            .evaluate(None, "spec1", Some(&now), IndexMap::new(), None, false)
2493            .unwrap();
2494        assert_eq!(
2495            response1.results[0].result().expect("result").to_string(),
2496            "20"
2497        );
2498        let response2 = engine
2499            .evaluate(None, "spec2", Some(&now), IndexMap::new(), None, false)
2500            .unwrap();
2501        assert_eq!(
2502            response2.results[0].result().expect("result").to_string(),
2503            "15"
2504        );
2505    }
2506
2507    #[test]
2508    fn test_runtime_error_mapping() {
2509        let mut engine = Engine::new();
2510        engine
2511            .load([(
2512                SourceType::Path(Arc::new(std::path::PathBuf::from("test.lemma"))),
2513                r#"
2514        spec test
2515        data numerator: 10
2516        data denominator: 0
2517        rule division: numerator / denominator
2518    "#
2519                .to_string(),
2520            )])
2521            .unwrap();
2522
2523        let now = DateTimeValue::now();
2524        let result = engine.evaluate(None, "test", Some(&now), IndexMap::new(), None, false);
2525        // Division by zero returns a Veto (not an error)
2526        assert!(result.is_ok(), "Evaluation should succeed");
2527        let response = result.unwrap();
2528        let division_result = response
2529            .results
2530            .values()
2531            .find(|r| r.rule.name == "division");
2532        assert!(
2533            division_result.is_some(),
2534            "Should have division rule result"
2535        );
2536        let division = division_result.unwrap();
2537        assert!(division.vetoed);
2538        assert!(
2539            division
2540                .veto_reason
2541                .as_deref()
2542                .unwrap()
2543                .contains("Division by zero"),
2544            "Veto message should mention division by zero: {:?}",
2545            division.veto_reason
2546        );
2547    }
2548
2549    #[test]
2550    fn test_rules_sorted_by_source_order() {
2551        let mut engine = Engine::new();
2552        engine
2553            .load([(
2554                SourceType::Path(Arc::new(std::path::PathBuf::from("test.lemma"))),
2555                r#"
2556        spec test
2557        data a: 1
2558        data b: 2
2559        rule z: a + b
2560        rule y: a * b
2561        rule x: a - b
2562    "#
2563                .to_string(),
2564            )])
2565            .unwrap();
2566
2567        let now = DateTimeValue::now();
2568        let response = engine
2569            .evaluate(None, "test", Some(&now), IndexMap::new(), None, false)
2570            .unwrap();
2571        assert_eq!(response.results.len(), 3);
2572
2573        // Verify source positions increase (z < y < x)
2574        let z_pos = response
2575            .results
2576            .values()
2577            .find(|r| r.rule.name == "z")
2578            .unwrap()
2579            .rule
2580            .source_location
2581            .span
2582            .start;
2583        let y_pos = response
2584            .results
2585            .values()
2586            .find(|r| r.rule.name == "y")
2587            .unwrap()
2588            .rule
2589            .source_location
2590            .span
2591            .start;
2592        let x_pos = response
2593            .results
2594            .values()
2595            .find(|r| r.rule.name == "x")
2596            .unwrap()
2597            .rule
2598            .source_location
2599            .span
2600            .start;
2601
2602        assert!(z_pos < y_pos);
2603        assert!(y_pos < x_pos);
2604    }
2605
2606    #[test]
2607    fn test_rule_filtering_evaluates_dependencies() {
2608        let mut engine = Engine::new();
2609        engine
2610            .load([(
2611                SourceType::Path(Arc::new(std::path::PathBuf::from("test.lemma"))),
2612                r#"
2613        spec test
2614        data base: 100
2615        rule subtotal: base * 2
2616        rule tax: subtotal * 10%
2617        rule total: subtotal + tax
2618    "#
2619                .to_string(),
2620            )])
2621            .unwrap();
2622
2623        let now = DateTimeValue::now();
2624        let response = engine
2625            .evaluate(
2626                None,
2627                "test",
2628                Some(&now),
2629                IndexMap::new(),
2630                Some(&["total".to_string()]),
2631                false,
2632            )
2633            .unwrap();
2634
2635        assert_eq!(response.results.len(), 1);
2636        assert_eq!(response.results.keys().next().unwrap(), "total");
2637
2638        // But the value should be correct (dependencies were computed)
2639        let total = response.results.values().next().unwrap();
2640        assert_eq!(total.result().expect("result").to_string(), "220");
2641    }
2642
2643    // -------------------------------------------------------------------
2644    // Pre-resolved dependency tests (Engine never fetches from registry)
2645    // -------------------------------------------------------------------
2646
2647    use crate::parsing::ast::DateTimeValue;
2648
2649    #[test]
2650    fn pre_resolved_deps_in_file_map_evaluates_external_spec() {
2651        let mut engine = Engine::new();
2652
2653        engine
2654            .load([(
2655                SourceType::Dependency("@org/project".to_string()),
2656                "repo @org/project\nspec helper\ndata quantity: 42".to_string(),
2657            )])
2658            .expect("should load dependency files");
2659
2660        engine
2661            .load([(
2662                SourceType::Path(Arc::new(std::path::PathBuf::from("main.lemma"))),
2663                r#"spec main_spec
2664uses external: @org/project helper
2665rule value: external.quantity"#
2666                    .to_string(),
2667            )])
2668            .expect("should succeed with pre-resolved deps");
2669
2670        let now = DateTimeValue::now();
2671        let response = engine
2672            .evaluate(None, "main_spec", Some(&now), IndexMap::new(), None, false)
2673            .expect("evaluate should succeed");
2674
2675        let value_result = response
2676            .results
2677            .get("value")
2678            .expect("rule 'value' should exist");
2679        assert_eq!(value_result.result().expect("result").to_string(), "42");
2680    }
2681
2682    #[test]
2683    fn show_with_repo_resolves_registry_spec() {
2684        let mut engine = Engine::new();
2685        engine
2686            .load([(
2687                SourceType::Dependency("@org/project".to_string()),
2688                "repo @org/project\nspec helper\ndata quantity: 42\nrule expose: quantity"
2689                    .to_string(),
2690            )])
2691            .expect("registry bundle loads");
2692
2693        engine
2694            .load([(
2695                SourceType::Path(Arc::new(std::path::PathBuf::from("main.lemma"))),
2696                r#"spec main_spec
2697data x: 1"#
2698                    .to_string(),
2699            )])
2700            .expect("main loads");
2701
2702        let now = DateTimeValue::now();
2703        let view = engine
2704            .show(Some("@org/project"), "helper", Some(&now))
2705            .expect("show for registry spec");
2706        assert!(view.data.contains_key("quantity"));
2707    }
2708
2709    #[test]
2710    fn load_no_external_refs_works() {
2711        let mut engine = Engine::new();
2712
2713        engine
2714            .load([(
2715                SourceType::Path(Arc::new(std::path::PathBuf::from("local.lemma"))),
2716                r#"spec local_only
2717data price: 100
2718rule doubled: price * 2"#
2719                    .to_string(),
2720            )])
2721            .expect("should succeed when there are no @... references");
2722
2723        let now = DateTimeValue::now();
2724        let response = engine
2725            .evaluate(None, "local_only", Some(&now), IndexMap::new(), None, false)
2726            .expect("evaluate should succeed");
2727
2728        let doubled = response.results.get("doubled").expect("doubled rule");
2729        assert_eq!(doubled.result().expect("result").to_string(), "200");
2730    }
2731
2732    #[test]
2733    fn unresolved_external_ref_without_deps_fails() {
2734        let mut engine = Engine::new();
2735
2736        let result = engine.load([(
2737            SourceType::Path(Arc::new(std::path::PathBuf::from("main.lemma"))),
2738            r#"spec main_spec
2739uses external: @org/project missing
2740rule value: external.quantity"#
2741                .to_string(),
2742        )]);
2743
2744        let errs = result.expect_err("Should fail when registry dep is not loaded");
2745        assert!(
2746            errs.iter()
2747                .any(|e| e.kind() == crate::ErrorKind::MissingRepository),
2748            "expected MissingRepository, got: {:?}",
2749            errs.iter().map(|e| e.kind()).collect::<Vec<_>>()
2750        );
2751    }
2752
2753    #[test]
2754    fn pre_resolved_deps_with_spec_and_type_refs() {
2755        let mut engine = Engine::new();
2756
2757        engine
2758            .load([(
2759                SourceType::Dependency("@org/example".to_string()),
2760                "repo @org/example\nspec helper\ndata value: 42".to_string(),
2761            )])
2762            .expect("should load helper file");
2763
2764        engine
2765        .load([(
2766                SourceType::Dependency("@iso/countries".to_string()),
2767                "repo @iso/countries\nspec alpha2\ndata code: text\n -> option \"NL\"\n -> option \"BE\"".to_string(),
2768            )])
2769            .expect("should load alpha2 file");
2770
2771        engine
2772            .load([(
2773                SourceType::Path(Arc::new(std::path::PathBuf::from("main.lemma"))),
2774                r#"spec registry_demo
2775uses @iso/countries alpha2
2776data country: alpha2.code
2777data unit_count: 5
2778uses @org/example helper
2779rule helper_value: helper.value
2780rule line_total: unit_count * 2
2781rule formatted: helper_value + 0"#
2782                    .to_string(),
2783            )])
2784            .expect("should succeed with pre-resolved spec and type deps");
2785
2786        let now = DateTimeValue::now();
2787        let response = engine
2788            .evaluate(
2789                None,
2790                "registry_demo",
2791                Some(&now),
2792                IndexMap::new(),
2793                None,
2794                false,
2795            )
2796            .expect("evaluate should succeed");
2797
2798        assert_eq!(
2799            response
2800                .results
2801                .get("helper_value")
2802                .expect("helper_value")
2803                .result()
2804                .expect("result"),
2805            "42"
2806        );
2807        let line = response
2808            .results
2809            .get("line_total")
2810            .expect("line_total")
2811            .result()
2812            .expect("result");
2813        assert_eq!(line, "10");
2814        assert_eq!(
2815            response
2816                .results
2817                .get("formatted")
2818                .expect("formatted")
2819                .result()
2820                .expect("result"),
2821            "42"
2822        );
2823    }
2824
2825    #[test]
2826    fn load_empty_labeled_source_is_error() {
2827        let mut engine = Engine::new();
2828        let err = engine
2829            .load([(
2830                SourceType::Path(Arc::new(std::path::PathBuf::from("  "))),
2831                "spec x\ndata a: 1".to_string(),
2832            )])
2833            .unwrap_err();
2834        assert!(err.errors.iter().any(|e| e.message().contains("non-empty")));
2835    }
2836
2837    #[test]
2838    fn add_dependency_files_accepts_registry_bundle_specs() {
2839        let mut engine = Engine::new();
2840        engine
2841            .load([(
2842                SourceType::Dependency("@org/my".to_string()),
2843                "repo @org/my\nspec helper\ndata x: 1".to_string(),
2844            )])
2845            .expect("dependency bundle specs should be accepted");
2846    }
2847
2848    #[test]
2849    fn user_load_rejects_reserved_embedded_stdlib_repository() {
2850        let mut engine = Engine::new();
2851        let batch = engine.load([(
2852            SourceType::Dependency(EMBEDDED_STDLIB_REPOSITORY.to_string()),
2853            "spec finance\ndata rate: ratio".to_string(),
2854        )]);
2855        assert!(
2856            batch.is_err(),
2857            "load must not write reserved lemma stdlib repo"
2858        );
2859        let msg = batch
2860            .unwrap_err()
2861            .errors
2862            .iter()
2863            .map(ToString::to_string)
2864            .collect::<Vec<_>>()
2865            .join("\n");
2866        assert!(
2867            msg.contains(EMBEDDED_STDLIB_REPOSITORY) && msg.contains("reserved"),
2868            "expected reserved-repo error, got: {msg}"
2869        );
2870
2871        let workspace = engine.load([(
2872            SourceType::Volatile,
2873            "repo lemma\nspec x\ndata a: 1".to_string(),
2874        )]);
2875        assert!(workspace.is_err(), "workspace repo lemma must be rejected");
2876        let msg = workspace
2877            .unwrap_err()
2878            .errors
2879            .iter()
2880            .map(ToString::to_string)
2881            .collect::<Vec<_>>()
2882            .join("\n");
2883        assert!(
2884            msg.contains(EMBEDDED_STDLIB_REPOSITORY) && msg.contains("reserved"),
2885            "expected reserved-repo error, got: {msg}"
2886        );
2887    }
2888
2889    #[test]
2890    fn load_returns_all_errors_not_just_first() {
2891        let mut engine = Engine::new();
2892
2893        let result = engine.load([(
2894            SourceType::Path(Arc::new(std::path::PathBuf::from("test.lemma"))),
2895            r#"spec demo
2896uses type_src: nonexistent_type_source
2897  -> with amount: 10
2898uses helper: nonexistent_spec
2899data price: 10
2900rule total: helper.value + price"#
2901                .to_string(),
2902        )]);
2903
2904        assert!(result.is_err(), "Should fail with multiple errors");
2905        let load_err = result.unwrap_err();
2906        assert!(
2907            load_err.errors.len() >= 2,
2908            "expected at least 2 errors (type + spec ref), got {}",
2909            load_err.errors.len()
2910        );
2911        let error_message = load_err
2912            .errors
2913            .iter()
2914            .map(ToString::to_string)
2915            .collect::<Vec<_>>()
2916            .join("; ");
2917
2918        assert!(
2919            error_message.contains("nonexistent_type_source"),
2920            "Should mention data import source spec. Got:\n{}",
2921            error_message
2922        );
2923        assert!(
2924            error_message.contains("nonexistent_spec"),
2925            "Should mention spec reference error about 'nonexistent_spec'. Got:\n{}",
2926            error_message
2927        );
2928    }
2929
2930    // ── Suggestion value type validation ────────────────────────────────
2931    // Planning must reject suggestion values that don't match the type.
2932    // These tests cover both primitives and named types (which the parser
2933    // can't validate because it doesn't resolve type names).
2934
2935    #[test]
2936    fn planning_rejects_invalid_number_default() {
2937        let mut engine = Engine::new();
2938        let result = engine.load([(
2939            SourceType::Path(Arc::new(std::path::PathBuf::from("t.lemma"))),
2940            "spec t\ndata x: number -> suggest \"10 $$\"]\nrule r: x".to_string(),
2941        )]);
2942        assert!(
2943            result.is_err(),
2944            "must reject non-numeric suggestion on number type"
2945        );
2946    }
2947
2948    #[test]
2949    fn planning_rejects_text_literal_as_number_default() {
2950        // `suggest "10"` produces a typed `CommandArg::Literal(Value::Text("10"))`.
2951        // Planning matches on the literal's variant — a `Text` literal is rejected
2952        // where a `Number` literal is required, even though `"10"` would parse as
2953        // a valid `Decimal` if coerced.
2954        let mut engine = Engine::new();
2955        let result = engine.load([(
2956            SourceType::Path(Arc::new(std::path::PathBuf::from("t.lemma"))),
2957            "spec t\ndata x: number -> suggest \"10\"]\nrule r: x".to_string(),
2958        )]);
2959        assert!(
2960            result.is_err(),
2961            "must reject text literal \"10\" as suggestion for number type"
2962        );
2963    }
2964
2965    #[test]
2966    fn planning_rejects_invalid_boolean_default() {
2967        let mut engine = Engine::new();
2968        let result = engine.load([(
2969            SourceType::Path(Arc::new(std::path::PathBuf::from("t.lemma"))),
2970            "spec t\ndata x: [boolean -> suggest \"maybe\"]\nrule r: x".to_string(),
2971        )]);
2972        assert!(
2973            result.is_err(),
2974            "must reject non-boolean suggestion on boolean type"
2975        );
2976    }
2977
2978    #[test]
2979    fn planning_rejects_invalid_named_type_default() {
2980        // Named type: the parser can't validate this, only planning can.
2981        let mut engine = Engine::new();
2982        let result = engine.load([(SourceType::Path(Arc::new(std::path::PathBuf::from("t.lemma"))), "spec t\ndata custom: number -> minimum 0\ndata x: [custom -> suggest \"abc\"]\nrule r: x".to_string())]);
2983        assert!(
2984            result.is_err(),
2985            "must reject non-numeric suggestion on named number type"
2986        );
2987    }
2988
2989    #[test]
2990    fn context_merges_cross_file_repo_identities() {
2991        let mut engine = Engine::new();
2992
2993        // Load two files with the same named repo, but different spec names.
2994        engine
2995            .load([(
2996                SourceType::Path(Arc::new(std::path::PathBuf::from("file1.lemma"))),
2997                "repo shared\nspec a\ndata x: 1".to_string(),
2998            )])
2999            .expect("first file should load");
3000
3001        engine
3002            .load([(
3003                SourceType::Path(Arc::new(std::path::PathBuf::from("file2.lemma"))),
3004                "repo shared\nspec b\ndata y: 2".to_string(),
3005            )])
3006            .expect("second file should load");
3007
3008        // Both specs should land under the same repo entry.
3009        // Workspace, embedded stdlib (`lemma`), plus the "shared" repo.
3010        assert_eq!(
3011            engine.context.repositories().len(),
3012            3,
3013            "should have workspace, stdlib repository, and one named user repository"
3014        );
3015
3016        let shared_repo = engine
3017            .context
3018            .find_repository("shared")
3019            .expect("shared repo should exist");
3020        let shared_specs = engine.context.repositories().get(&shared_repo).unwrap();
3021        assert_eq!(
3022            shared_specs.len(),
3023            2,
3024            "shared repo should contain both specs"
3025        );
3026        assert!(shared_specs.contains_key("a"));
3027        assert!(shared_specs.contains_key("b"));
3028
3029        // Loading a dependency with the same repo name should be rejected.
3030        let dependency_result = engine.load([(
3031            SourceType::Dependency("@some/dep".to_string()),
3032            "repo shared\nspec c\ndata z: 3".to_string(),
3033        )]);
3034        assert!(
3035            dependency_result.is_err(),
3036            "dependency with an existing repo name must be rejected"
3037        );
3038
3039        let result = engine.load([(
3040            SourceType::Path(Arc::new(std::path::PathBuf::from("file2.lemma"))),
3041            "repo shared\nspec a\ndata y: 2".to_string(),
3042        )]);
3043
3044        assert!(
3045            result.is_err(),
3046            "should reject duplicate spec name in same repo"
3047        );
3048        let load_err = result.unwrap_err();
3049        assert_eq!(
3050            load_err.errors.len(),
3051            2,
3052            "duplicate spec must error on both declaring sources, got: {:?}",
3053            load_err.errors
3054        );
3055        let joined = load_err
3056            .errors
3057            .iter()
3058            .map(|e| e.to_string())
3059            .collect::<Vec<_>>()
3060            .join("\n");
3061        assert!(
3062            joined.contains("Duplicate spec 'a'"),
3063            "error should mention duplicate spec, got: {joined}"
3064        );
3065        let paths: Vec<String> = load_err
3066            .errors
3067            .iter()
3068            .map(|err| {
3069                err.location()
3070                    .expect("duplicate errors must have source")
3071                    .source_type
3072                    .to_string()
3073            })
3074            .collect();
3075        assert!(
3076            paths.iter().any(|p| p == "file1.lemma"),
3077            "first declaring file must get conflict diagnostic, got paths: {paths:?}"
3078        );
3079        assert!(
3080            paths.iter().any(|p| p == "file2.lemma"),
3081            "incoming file must get conflict diagnostic, got paths: {paths:?}"
3082        );
3083    }
3084
3085    #[test]
3086    fn test_list_structure() {
3087        let mut engine = Engine::new();
3088        engine
3089            .load([(
3090                SourceType::Path(Arc::new(std::path::PathBuf::from("file1.lemma"))),
3091                "repo shared\nspec a\ndata x: 1\nrule r: x".to_string(),
3092            )])
3093            .expect("file should load");
3094
3095        let repos = engine.specs();
3096        let shared_repo = repos
3097            .iter()
3098            .find(|r| r.repository.as_deref() == Some("shared"))
3099            .expect("shared repo in list");
3100        assert_eq!(shared_repo.specs.len(), 1);
3101        assert_eq!(shared_repo.specs[0].name, "a");
3102    }
3103
3104    fn path_st(name: &str) -> SourceType {
3105        SourceType::Path(Arc::new(std::path::PathBuf::from(name)))
3106    }
3107
3108    #[test]
3109    fn remove_none_removes_version_active_at_now() {
3110        let mut engine = Engine::new();
3111        engine
3112            .load([(
3113                path_st("t.lemma"),
3114                "spec t\ndata v: 1\nrule r: v\n\nspec t 2099-01-01\ndata v: 2\nrule r: v\n"
3115                    .to_string(),
3116            )])
3117            .expect("load");
3118        engine
3119            .remove(None, "t", None)
3120            .expect("remove active-at now (origin while before 2099)");
3121        let workspace = engine
3122            .specs()
3123            .into_iter()
3124            .find(|r| r.repository.is_none())
3125            .expect("workspace");
3126        assert_eq!(workspace.specs.iter().filter(|s| s.name == "t").count(), 1);
3127        assert!(
3128            workspace
3129                .specs
3130                .iter()
3131                .any(|s| s.name == "t" && s.effective_from.is_some()),
3132            "dated version must remain"
3133        );
3134    }
3135
3136    #[test]
3137    fn remove_none_errors_when_no_version_active_at_now() {
3138        let mut engine = Engine::new();
3139        engine
3140            .load([(
3141                path_st("t.lemma"),
3142                "spec t 2099-01-01\ndata v: 1\nrule r: v\n".to_string(),
3143            )])
3144            .expect("load");
3145        let err = engine
3146            .remove(None, "t", None)
3147            .expect_err("no version active at now");
3148        assert_eq!(err.kind(), crate::ErrorKind::Request);
3149        assert!(
3150            engine.show(None, "t", Some(&date(2099, 1, 1))).is_ok(),
3151            "future version must remain"
3152        );
3153    }
3154
3155    #[test]
3156    fn update_origin_code_keeps_later_version() {
3157        let mut engine = Engine::new();
3158        let st = path_st("t.lemma");
3159        engine
3160            .load([(
3161                st.clone(),
3162                "spec t\ndata v: 1\nrule r: v\n\nspec t 2099-01-01\ndata v: 2\nrule r: v\n"
3163                    .to_string(),
3164            )])
3165            .expect("load");
3166        engine
3167            .update(
3168                None,
3169                "spec t\ndata v: 9\nrule r: v\n\nspec t 2099-01-01\ndata v: 2\nrule r: v\n"
3170                    .to_string(),
3171                st,
3172            )
3173            .expect("update origin body while keeping later version in buffer");
3174        let workspace = engine
3175            .specs()
3176            .into_iter()
3177            .find(|r| r.repository.is_none())
3178            .expect("workspace");
3179        assert_eq!(workspace.specs.iter().filter(|s| s.name == "t").count(), 2);
3180        let now = DateTimeValue::now();
3181        let response = engine
3182            .evaluate(None, "t", Some(&now), IndexMap::new(), None, false)
3183            .expect("evaluate origin");
3184        assert_eq!(
3185            response.results.get("r").and_then(|r| r.result()),
3186            Some("9")
3187        );
3188    }
3189
3190    #[test]
3191    fn update_path_prunes_dropped_version() {
3192        let mut engine = Engine::new();
3193        let st = path_st("t.lemma");
3194        engine
3195            .load([(
3196                st.clone(),
3197                "spec t\ndata v: 1\nrule r: v\n\nspec t 2025-06-01\ndata v: 2\nrule r: v\n"
3198                    .to_string(),
3199            )])
3200            .expect("load");
3201        engine
3202            .update(None, "spec t\ndata v: 1\nrule r: v\n".to_string(), st)
3203            .expect("prune second version");
3204        let workspace = engine
3205            .specs()
3206            .into_iter()
3207            .find(|r| r.repository.is_none())
3208            .expect("workspace");
3209        assert_eq!(workspace.specs.iter().filter(|s| s.name == "t").count(), 1);
3210        assert!(workspace
3211            .specs
3212            .iter()
3213            .any(|s| s.name == "t" && s.effective_from.is_none()));
3214    }
3215
3216    #[test]
3217    fn update_volatile_does_not_prune_sibling() {
3218        let mut engine = Engine::new();
3219        engine
3220            .load([(
3221                SourceType::Volatile,
3222                "spec a\ndata v: 1\nrule r: v\n\nspec b\ndata v: 2\nrule r: v\n".to_string(),
3223            )])
3224            .expect("load");
3225        engine
3226            .update(
3227                None,
3228                "spec a\ndata v: 3\nrule r: v\n".to_string(),
3229                SourceType::Volatile,
3230            )
3231            .expect("update a");
3232        let workspace = engine
3233            .specs()
3234            .into_iter()
3235            .find(|r| r.repository.is_none())
3236            .expect("workspace");
3237        assert!(workspace.specs.iter().any(|s| s.name == "a"));
3238        assert!(workspace.specs.iter().any(|s| s.name == "b"));
3239    }
3240
3241    #[test]
3242    fn update_upserts_new_identity() {
3243        let mut engine = Engine::new();
3244        let st = path_st("t.lemma");
3245        engine
3246            .load([(st.clone(), "spec a\ndata v: 1\nrule r: v\n".to_string())])
3247            .expect("load");
3248        engine
3249            .update(
3250                None,
3251                "spec a\ndata v: 1\nrule r: v\n\nspec b\ndata v: 2\nrule r: v\n".to_string(),
3252                st,
3253            )
3254            .expect("upsert b");
3255        let workspace = engine
3256            .specs()
3257            .into_iter()
3258            .find(|r| r.repository.is_none())
3259            .expect("workspace");
3260        assert!(workspace.specs.iter().any(|s| s.name == "a"));
3261        assert!(workspace.specs.iter().any(|s| s.name == "b"));
3262    }
3263
3264    #[test]
3265    fn update_cross_path_identity_is_error() {
3266        let mut engine = Engine::new();
3267        engine
3268            .load([(
3269                path_st("a.lemma"),
3270                "spec conflict\ndata v: 1\nrule r: v\n".to_string(),
3271            )])
3272            .expect("load a");
3273        let err = engine
3274            .update(
3275                None,
3276                "spec conflict\ndata v: 2\nrule r: v\n".to_string(),
3277                path_st("b.lemma"),
3278            )
3279            .expect_err("cross-path identity");
3280        let joined: String = err
3281            .errors
3282            .iter()
3283            .map(|e| e.to_string())
3284            .collect::<Vec<_>>()
3285            .join("\n");
3286        assert!(
3287            joined.contains("Duplicate spec") && joined.contains("also declared"),
3288            "expected duplicate across paths, got: {joined}"
3289        );
3290        assert!(
3291            engine.show(None, "conflict", None).is_ok(),
3292            "failed cross-path update must leave the original identity loaded"
3293        );
3294    }
3295
3296    #[test]
3297    fn update_empty_dependency_prunes_all_specs_of_source() {
3298        let mut engine = Engine::new();
3299        let st = SourceType::Dependency("@org/dep".to_string());
3300        engine
3301            .load([(
3302                st.clone(),
3303                "repo @org/dep\n\nspec a\ndata v: 1\nrule r: v\n\nspec b\ndata v: 2\nrule r: v\n"
3304                    .to_string(),
3305            )])
3306            .expect("load");
3307        engine
3308            .update(None, "   \n".to_string(), st)
3309            .expect("empty dependency update prunes");
3310        let listed = engine.specs();
3311        assert!(
3312            !listed.iter().any(|r| {
3313                r.repository.as_deref() == Some("@org/dep")
3314                    && r.specs.iter().any(|s| s.name == "a" || s.name == "b")
3315            }),
3316            "empty dependency update must remove every live row of that source"
3317        );
3318    }
3319
3320    #[test]
3321    fn failed_apply_leaves_list_source_and_run_unchanged() {
3322        let mut engine = Engine::new();
3323        engine
3324            .load([(
3325                SourceType::Volatile,
3326                "spec price\ndata amount: number\nrule total: amount\n".to_string(),
3327            )])
3328            .expect("load");
3329        let before_repositories = engine.specs();
3330        let before_source = engine.source(None, Some("price"), None).expect("source");
3331        let now = DateTimeValue::now();
3332        let before = engine
3333            .evaluate(
3334                None,
3335                "price",
3336                Some(&now),
3337                [("amount".to_string(), EvaluateDataValue::from("4"))]
3338                    .into_iter()
3339                    .collect(),
3340                None,
3341                false,
3342            )
3343            .expect("evaluate");
3344        let failed = engine.load([(
3345            SourceType::Volatile,
3346            "spec price\ndata amount: number\nrule total: amount +\n".to_string(),
3347        )]);
3348        assert!(failed.is_err(), "invalid spec must fail planning");
3349        assert_eq!(engine.specs(), before_repositories);
3350        assert_eq!(
3351            engine.source(None, Some("price"), None).expect("source"),
3352            before_source
3353        );
3354        let after = engine
3355            .evaluate(
3356                None,
3357                "price",
3358                Some(&now),
3359                [("amount".to_string(), EvaluateDataValue::from("4"))]
3360                    .into_iter()
3361                    .collect(),
3362                None,
3363                false,
3364            )
3365            .expect("evaluate after failed load");
3366        assert_eq!(
3367            after.results.get("total").expect("total").result,
3368            before.results.get("total").expect("total").result
3369        );
3370    }
3371
3372    #[test]
3373    fn update_empty_path_prunes_all_specs_of_source() {
3374        let mut engine = Engine::new();
3375        let st = path_st("t.lemma");
3376        engine
3377            .load([(
3378                st.clone(),
3379                "spec a\ndata v: 1\nrule r: v\n\nspec b\ndata v: 2\nrule r: v\n".to_string(),
3380            )])
3381            .expect("load");
3382        engine
3383            .update(None, "   \n".to_string(), st)
3384            .expect("empty path update prunes");
3385        let workspace = engine
3386            .specs()
3387            .into_iter()
3388            .find(|r| r.repository.is_none())
3389            .expect("workspace");
3390        assert!(
3391            !workspace
3392                .specs
3393                .iter()
3394                .any(|s| s.name == "a" || s.name == "b"),
3395            "empty path update must remove every live row of that source"
3396        );
3397    }
3398
3399    #[test]
3400    fn update_empty_volatile_is_error() {
3401        let mut engine = Engine::new();
3402        engine
3403            .load([(
3404                SourceType::Volatile,
3405                "spec a\ndata v: 1\nrule r: v\n".to_string(),
3406            )])
3407            .expect("load");
3408        let err = engine
3409            .update(None, "   \n".to_string(), SourceType::Volatile)
3410            .expect_err("empty volatile update");
3411        assert!(
3412            err.errors
3413                .iter()
3414                .any(|e| e.to_string().contains("at least one spec")),
3415            "got: {:?}",
3416            err.errors
3417        );
3418        assert!(
3419            engine.show(None, "a", None).is_ok(),
3420            "failed empty volatile update must leave the original identity loaded"
3421        );
3422    }
3423
3424    #[test]
3425    fn update_repository_param_mismatch_is_error() {
3426        let mut engine = Engine::new();
3427        let st = path_st("t.lemma");
3428        engine
3429            .load([(
3430                st.clone(),
3431                "repo other\nspec a\ndata v: 1\nrule r: v\n".to_string(),
3432            )])
3433            .expect("load");
3434        let err = engine
3435            .update(
3436                Some("expected"),
3437                "repo other\nspec a\ndata v: 2\nrule r: v\n".to_string(),
3438                st,
3439            )
3440            .expect_err("mismatch");
3441        assert!(
3442            err.errors
3443                .iter()
3444                .any(|e| e.to_string().contains("does not match")),
3445            "got: {:?}",
3446            err.errors
3447        );
3448    }
3449
3450    #[test]
3451    fn update_rollback_restores_pruned_and_replaced() {
3452        let mut engine = Engine::new();
3453        let dep = path_st("dep.lemma");
3454        let consumer = path_st("consumer.lemma");
3455        engine
3456            .load([
3457                (
3458                    dep.clone(),
3459                    "spec dep\ndata v: 1\nrule r: v\n\nspec dep 2025-06-01\ndata v: 2\nrule r: v\n"
3460                        .to_string(),
3461                ),
3462                (
3463                    consumer,
3464                    "spec consumer\nuses d: dep\nrule out: d.r\n".to_string(),
3465                ),
3466            ])
3467            .expect("load");
3468        let before = engine.specs();
3469        let err = engine
3470            .update(
3471                None,
3472                "spec dep\ndata other: 5\nrule unrelated: other\n".to_string(),
3473                dep,
3474            )
3475            .expect_err("consumer must break");
3476        assert!(!err.errors.is_empty());
3477        let after = engine.specs();
3478        assert_eq!(after.len(), before.len(), "repository count must match");
3479        for (before_repo, after_repo) in before.iter().zip(after.iter()) {
3480            assert_eq!(before_repo.repository, after_repo.repository);
3481            let mut before_specs = before_repo.specs.clone();
3482            let mut after_specs = after_repo.specs.clone();
3483            before_specs
3484                .sort_by(|a, b| (&a.name, &a.effective_from).cmp(&(&b.name, &b.effective_from)));
3485            after_specs
3486                .sort_by(|a, b| (&a.name, &a.effective_from).cmp(&(&b.name, &b.effective_from)));
3487            assert_eq!(
3488                before_specs, after_specs,
3489                "failed update must restore spec versions for {:?}",
3490                before_repo.repository
3491            );
3492        }
3493        let now = DateTimeValue::now();
3494        engine
3495            .evaluate(None, "consumer", Some(&now), IndexMap::new(), None, false)
3496            .expect("consumer still runs after rollback");
3497        assert!(
3498            engine.show(None, "dep", Some(&date(2025, 6, 1))).is_ok(),
3499            "pruned later dep version must be restored"
3500        );
3501    }
3502
3503    fn finance_result(engine: &Engine) -> String {
3504        let now = DateTimeValue::now();
3505        engine
3506            .evaluate(None, "finance", Some(&now), IndexMap::new(), None, false)
3507            .expect("finance evaluates")
3508            .results
3509            .values()
3510            .next()
3511            .expect("one result")
3512            .result()
3513            .expect("result")
3514            .to_string()
3515    }
3516
3517    #[test]
3518    fn update_pasted_duplicate_identity_is_error() {
3519        let mut engine = Engine::new();
3520        let st = path_st("finance.lemma");
3521        engine
3522            .load([(
3523                st.clone(),
3524                "spec finance\ndata v: 1\nrule r: 1\n".to_string(),
3525            )])
3526            .expect("load");
3527        let err = engine
3528            .update(
3529                None,
3530                "spec finance\ndata v: 1\nrule r: 1\n\nspec finance\ndata v: 2\nrule r: 2\n"
3531                    .to_string(),
3532                st,
3533            )
3534            .expect_err("pasted duplicate identity must be rejected");
3535        let joined: String = err
3536            .errors
3537            .iter()
3538            .map(ToString::to_string)
3539            .collect::<Vec<_>>()
3540            .join("\n");
3541        assert!(
3542            joined.contains("Duplicate spec 'finance'"),
3543            "expected duplicate error, got: {joined}"
3544        );
3545        assert_eq!(
3546            finance_result(&engine),
3547            "1",
3548            "original spec must stay active"
3549        );
3550    }
3551
3552    #[test]
3553    fn update_duplicate_identity_both_changed_is_error_not_panic() {
3554        let mut engine = Engine::new();
3555        let st = path_st("finance.lemma");
3556        engine
3557            .load([(
3558                st.clone(),
3559                "spec finance\ndata v: 1\nrule r: 1\n".to_string(),
3560            )])
3561            .expect("load");
3562        let err = engine
3563            .update(
3564                None,
3565                "spec finance\ndata v: 2\nrule r: 2\n\nspec finance\ndata v: 3\nrule r: 3\n"
3566                    .to_string(),
3567                st,
3568            )
3569            .expect_err("duplicate identity must be rejected");
3570        let joined: String = err
3571            .errors
3572            .iter()
3573            .map(ToString::to_string)
3574            .collect::<Vec<_>>()
3575            .join("\n");
3576        assert!(
3577            joined.contains("Duplicate spec 'finance'"),
3578            "expected duplicate error, got: {joined}"
3579        );
3580        assert_eq!(
3581            finance_result(&engine),
3582            "1",
3583            "original spec must stay active"
3584        );
3585    }
3586
3587    #[test]
3588    fn update_reports_every_duplicate_identity() {
3589        let mut engine = Engine::new();
3590        let err = engine
3591            .update(
3592                None,
3593                "spec finance\ndata v: 1\nrule r: 1\n\nspec finance\ndata v: 2\nrule r: 2\n\nspec policies\ndata v: 1\nrule r: 1\n\nspec policies\ndata v: 2\nrule r: 2\n"
3594                    .to_string(),
3595                path_st("policies.lemma"),
3596            )
3597            .expect_err("duplicate identities must be rejected");
3598        let joined: String = err
3599            .errors
3600            .iter()
3601            .map(ToString::to_string)
3602            .collect::<Vec<_>>()
3603            .join("\n");
3604        assert!(
3605            joined.contains("Duplicate spec 'finance'"),
3606            "expected finance duplicate, got: {joined}"
3607        );
3608        assert!(
3609            joined.contains("Duplicate spec 'policies'"),
3610            "expected policies duplicate, got: {joined}"
3611        );
3612    }
3613
3614    #[test]
3615    fn update_identical_bytes_succeeds() {
3616        let mut engine = Engine::new();
3617        let st = path_st("t.lemma");
3618        let code = "spec t\ndata v: 1\nrule r: v\n".to_string();
3619        engine.load([(st.clone(), code.clone())]).expect("load");
3620        let before = engine.show(None, "t", None).expect("show before");
3621        engine.update(None, code, st).expect("identical update");
3622        let after = engine.show(None, "t", None).expect("show after");
3623        assert_eq!(before.meta, after.meta);
3624        assert_eq!(
3625            before.rules.keys().collect::<Vec<_>>(),
3626            after.rules.keys().collect::<Vec<_>>()
3627        );
3628    }
3629
3630    /// Body-only edit of one temporal version must not spuriously reject a consumer
3631    /// whose window overlaps only the non-dirty sibling version.
3632    #[test]
3633    fn update_slice_mode_keeps_consumer_overlapping_sibling_version() {
3634        let mut engine = Engine::new();
3635        let dep = path_st("dep.lemma");
3636        let consumer = path_st("consumer.lemma");
3637        engine
3638            .load([
3639                (
3640                    dep.clone(),
3641                    "spec dep\ndata v: 1\nrule r: v\n\nspec dep 2025-06-01\ndata v: 2\nrule r: v\n"
3642                        .to_string(),
3643                ),
3644                (
3645                    consumer,
3646                    "spec consumer\nuses d: dep\nrule out: d.r\n\nspec consumer 2025-06-01\nuses d: dep\nrule out: d.r\n"
3647                        .to_string(),
3648                ),
3649            ])
3650            .expect("load");
3651        engine
3652            .update(
3653                None,
3654                "spec dep\ndata v: 1\nrule r: v\n\nspec dep 2025-06-01\ndata v: 9\nrule r: v\n"
3655                    .to_string(),
3656                dep,
3657            )
3658            .expect("body-only edit of later dep version must keep consumers valid");
3659        let before_breakpoint = date(2025, 1, 15);
3660        let response = engine
3661            .evaluate(
3662                None,
3663                "consumer",
3664                Some(&before_breakpoint),
3665                IndexMap::new(),
3666                None,
3667                false,
3668            )
3669            .expect("origin consumer still runs against non-dirty dep version");
3670        assert_eq!(
3671            response.results.get("out").and_then(|r| r.result()),
3672            Some("1")
3673        );
3674        let after_breakpoint = date(2025, 7, 1);
3675        let response = engine
3676            .evaluate(
3677                None,
3678                "consumer",
3679                Some(&after_breakpoint),
3680                IndexMap::new(),
3681                None,
3682                false,
3683            )
3684            .expect("later consumer runs against dirty dep version");
3685        assert_eq!(
3686            response.results.get("out").and_then(|r| r.result()),
3687            Some("9")
3688        );
3689    }
3690
3691    /// Body-only edit that introduces interface drift vs a sibling version must fail
3692    /// the same way a cold load of the resulting files would.
3693    #[test]
3694    fn update_slice_mode_rejects_interface_drift_vs_sibling_version() {
3695        let mut engine = Engine::new();
3696        let dep = path_st("dep.lemma");
3697        let consumer = path_st("consumer.lemma");
3698        engine
3699            .load([
3700                (
3701                    dep.clone(),
3702                    "spec dep\ndata v: 1\nrule r: v\n\nspec dep 2025-06-01\ndata v: 2\nrule r: v\n"
3703                        .to_string(),
3704                ),
3705                (
3706                    consumer.clone(),
3707                    "spec consumer\nuses d: dep\nrule out: d.r\n".to_string(),
3708                ),
3709            ])
3710            .expect("load");
3711        let err = engine
3712            .update(
3713                None,
3714                "spec dep\ndata v: 1\nrule r: v\n\nspec dep 2025-06-01\ndata v: \"x\"\nrule r: v\n"
3715                    .to_string(),
3716                dep.clone(),
3717            )
3718            .expect_err("drift between dep versions must fail incremental update");
3719        assert!(
3720            err.errors.iter().any(|e| {
3721                let msg = e.to_string();
3722                msg.contains("interface") || msg.contains("changed")
3723            }),
3724            "expected interface-drift error, got: {:?}",
3725            err.errors
3726        );
3727
3728        let mut cold = Engine::new();
3729        let cold_err = cold
3730            .load([
3731                (
3732                    dep,
3733                    "spec dep\ndata v: 1\nrule r: v\n\nspec dep 2025-06-01\ndata v: \"x\"\nrule r: v\n"
3734                        .to_string(),
3735                ),
3736                (
3737                    consumer,
3738                    "spec consumer\nuses d: dep\nrule out: d.r\n".to_string(),
3739                ),
3740            ])
3741            .expect_err("cold load must also reject the drift");
3742        assert!(
3743            cold_err.errors.iter().any(|e| {
3744                let msg = e.to_string();
3745                msg.contains("interface") || msg.contains("changed")
3746            }),
3747            "expected interface-drift error on cold load, got: {:?}",
3748            cold_err.errors
3749        );
3750    }
3751
3752    /// Body-only edit of one temporal version that fails to plan must Error, not panic,
3753    /// when a healthy sibling version remains and a consumer depends on the set.
3754    #[test]
3755    fn update_slice_mode_planning_error_on_dirty_version_is_error_not_panic() {
3756        let mut engine = Engine::new();
3757        let dep = path_st("dep.lemma");
3758        let consumer = path_st("consumer.lemma");
3759        engine
3760            .load([
3761                (
3762                    dep.clone(),
3763                    "spec dep\ndata v: 1\nrule r: v\n\nspec dep 2025-06-01\ndata v: 2\nrule r: v\n"
3764                        .to_string(),
3765                ),
3766                (
3767                    consumer,
3768                    "spec consumer\nuses d: dep\nrule out: d.r\n".to_string(),
3769                ),
3770            ])
3771            .expect("load");
3772        let err = engine
3773            .update(
3774                None,
3775                "spec dep\ndata v: 1\nrule r: v\n\nspec dep 2025-06-01\ndata v: 2\nrule r: v + nope\n"
3776                    .to_string(),
3777                dep,
3778            )
3779            .expect_err("planning error on dirty version must be Err, not panic");
3780        assert!(!err.errors.is_empty());
3781        let now = DateTimeValue::now();
3782        engine
3783            .evaluate(None, "consumer", Some(&now), IndexMap::new(), None, false)
3784            .expect("failed update must leave previous engine state intact");
3785    }
3786}