Skip to main content

memstead_base/engine/lifecycle/
schema.rs

1//! Schema install and validation: staging a sealed package, validating its shape and its exemplars, and installing it into the workspace.
2
3use super::*;
4
5impl Engine {
6    /// Install a schema package onto the workspace's git-branch backend —
7    /// the unified `__MEMSTEAD:schemas/<name>@<version>/` ref. `files`
8    /// are `(relative-path, bytes)` pairs (`schema.yaml`,
9    /// `types/<t>.yaml`, optional `mem-template.json`). Returns the
10    /// resulting commit sha; idempotent at the storage layer (an
11    /// identical re-install produces no new commit).
12    ///
13    /// Folder workspaces install schemas by writing under
14    /// `<workspace>/.memstead/schemas/` directly; this is the git-branch
15    /// path, where the engine owns the mem-repo and the write must
16    /// route through it. Errors when no git-branch ops are wired
17    /// or no git-branch mount exists to resolve the shared
18    /// mem-repo gitdir from. The caller reloads (or restarts) to pick
19    /// the new schema into the resolution catalogue.
20    pub fn install_schema(
21        &self,
22        name: &str,
23        version: &str,
24        files: &[(String, Vec<u8>)],
25    ) -> Result<String, EngineError> {
26        // Validation gate: the engine refuses to seal a package that the
27        // loader would reject or whose section headings cannot round-trip
28        // to their keys. Install time is the last moment the author can
29        // act — sealed schemas keep loading even when a later rule would
30        // refuse them, so nothing invalid may pass this point.
31        Self::validate_schema_package(name, version, files)?;
32        // Resolve the shared mem-repo gitdir: prefer a live git-branch
33        // mount's gitdir (authoritative — that is where the engine reads
34        // schemas from), falling back to the workspace's `mem-repo/.git`
35        // so a schema can be installed into an empty mem-repo *before*
36        // any mem pins it.
37        let gitdir = self
38            .mounts
39            .iter()
40            .find_map(|m| match &m.mount.storage {
41                crate::workspace::MountStorage::GitBranch { gitdir, .. } => Some(gitdir.clone()),
42                _ => None,
43            })
44            .or_else(|| {
45                self.workspace_root()
46                    .map(|r| r.join("mem-repo").join(".git"))
47            })
48            .ok_or_else(|| {
49                EngineError::Mem(
50                    "schema install requires a mem-repo workspace (no git-branch mount and \
51                     no workspace root to resolve the mem-repo gitdir)"
52                        .to_string(),
53                )
54            })?;
55        let ops = self.git_branch_ops.as_ref().ok_or_else(|| {
56            EngineError::Mem("git-branch ops are not wired on this engine".to_string())
57        })?;
58        // Seal the package AS-GIVEN: the format marker is a generation
59        // claim only the resolver can make (an authored directory source
60        // arrives already stamped; a legacy builtin or sealed source
61        // arrives unmarked, and absence IS its legacy claim). Stamping
62        // here mis-labelled legacy content as current and flipped every
63        // bare field's meaning in the sealed copy — the manufacturing
64        // defect an earlier plan removed.
65        (ops.write_schema)(&gitdir, name, version, files).map_err(EngineError::Backend)
66    }
67
68    /// Make a **sealed third-party** schema package resolvable in this
69    /// workspace — the install-time half of "a published mem installs
70    /// on the strength of the schema it carries".
71    ///
72    /// The package (package-relative files: `schema.yaml`,
73    /// `types/<t>.yaml`, `schema-format.json`) is written into the
74    /// workspace's local schema storage, the same storage
75    /// [`Self::install_schema`] writes to and the pin resolver reads —
76    /// so the mount that follows resolves without a fourth mechanism
77    /// and a second mem pinning the same schema finds it already
78    /// there. The loaded schema also lands in this engine's live
79    /// catalogue, so the caller mounts in the same process without a
80    /// reload.
81    ///
82    /// Two things it deliberately does NOT do. It does not run the
83    /// authoring gate ([`Self::validate_schema_package`]): these are a
84    /// third party's sealed bytes, the installing user cannot fix
85    /// them, and the archive validator has already admitted them under
86    /// the sealed reading — applying the authoring gate here would
87    /// make an archive that is valid to publish invalid to install.
88    /// And it does not append the format marker: presence of the
89    /// marker IS the package's metadata-polarity generation, so
90    /// injecting one would rewrite the meaning of bytes the publisher
91    /// sealed.
92    ///
93    /// Idempotent: a pin the engine can already resolve returns
94    /// [`SchemaStaging::AlreadyResolvable`] with nothing written.
95    ///
96    /// Shape-agnostic: on a workspace with no sealed-package storage (the
97    /// folder shape) the package is still read and checked against the
98    /// pin, so a broken embedded schema refuses before any mount side
99    /// effect, but nothing is written — the archive-backed mount that
100    /// follows resolves the vocabulary from the archive itself
101    /// ([`SchemaStaging::CarriedByArchive`]). What that shape forgoes is
102    /// the staged copy's extras: `memstead schema <pin>` rendering the
103    /// installed package, and a second, writable mem pinning it.
104    pub fn stage_sealed_schema(
105        &mut self,
106        mem: &str,
107        pin: &memstead_schema::SchemaRef,
108        files: &[(String, Vec<u8>)],
109    ) -> Result<SchemaStaging, EngineError> {
110        let catalogue: Vec<std::sync::Arc<memstead_schema::Schema>> = self
111            .workspace_schemas
112            .iter()
113            .chain(self.builtin_schemas.iter())
114            .cloned()
115            .collect();
116        if crate::engine::SchemaResolver::new(&catalogue)
117            .resolve(pin)
118            .is_ok()
119        {
120            return Ok(SchemaStaging::AlreadyResolvable);
121        }
122        if files.is_empty() {
123            // Nothing embedded to stage. The caller's mount attempt
124            // reports the unresolved pin with its own source trail —
125            // that IS the actionable error here.
126            return Ok(SchemaStaging::NoEmbeddedSchema);
127        }
128
129        let unloadable = |reason: String| EngineError::EmbeddedSchemaInvalid {
130            mem: mem.to_string(),
131            pin: pin.as_display(),
132            reason,
133        };
134        // Read it exactly as the local schema source will read it back
135        // — one sealed reader, so admission and re-read cannot diverge.
136        let schema =
137            memstead_schema::load_sealed_package(files).map_err(|e| unloadable(e.to_string()))?;
138        let (name, version) = schema.id();
139        if name != pin.name || version != pin.version {
140            return Err(unloadable(format!(
141                "the package declares '{name}@{version}' but the mem pins {}",
142                pin.as_display()
143            )));
144        }
145
146        if self.sealed_schema_gitdir().is_none() {
147            return Ok(SchemaStaging::CarriedByArchive);
148        }
149        self.write_to_local_schema_source(&name, &version.to_string(), files)?;
150        self.workspace_schemas.push(std::sync::Arc::new(schema));
151        Ok(SchemaStaging::Staged)
152    }
153
154    /// Every git directory this engine reads sealed schema packages
155    /// from: [`crate::workspace::schema_registry_gitdirs`] over the live
156    /// mounts and the quarantined ones. A quarantined mount counts
157    /// because its quarantine is often the unresolved pin a later
158    /// install into its own repository repairs.
159    pub(crate) fn schema_registry_gitdirs(&self) -> Vec<PathBuf> {
160        crate::workspace::schema_registry_gitdirs(
161            self.mounts
162                .iter()
163                .map(|m| &m.mount)
164                .chain(self.quarantined.iter().map(|q| &q.mount)),
165            self.workspace_root(),
166        )
167    }
168
169    /// The gitdir that holds sealed third-party packages (the
170    /// `__MEMSTEAD:schemas/` ref): the first git-branch mount's, else the
171    /// workspace's `mem-repo/.git`. `None` on a folder-shaped workspace,
172    /// whose `.memstead/schemas/` is the authoring tier and never holds
173    /// sealed bytes.
174    fn sealed_schema_gitdir(&self) -> Option<PathBuf> {
175        self.mounts
176            .iter()
177            .find_map(|m| match &m.mount.storage {
178                crate::workspace::MountStorage::GitBranch { gitdir, .. } => Some(gitdir.clone()),
179                _ => None,
180            })
181            .or_else(|| {
182                self.workspace_root()
183                    .map(|r| r.join("mem-repo").join(".git"))
184            })
185            .filter(|g| g.is_dir())
186    }
187
188    /// Write a schema package into the workspace's local schema
189    /// storage — the git-branch `__MEMSTEAD:schemas/` ref when the
190    /// workspace is mem-repo-shaped. Shares
191    /// [`Self::install_schema`]'s gitdir resolution so authored and
192    /// staged packages land in one place.
193    fn write_to_local_schema_source(
194        &self,
195        name: &str,
196        version: &str,
197        files: &[(String, Vec<u8>)],
198    ) -> Result<(), EngineError> {
199        let gitdir = self.sealed_schema_gitdir().ok_or_else(|| {
200            EngineError::Mem(
201                "staging a schema requires a mem-repo workspace — the folder workspace's \
202                     `.memstead/schemas/` is the authoring tier and never holds sealed \
203                     third-party packages"
204                    .to_string(),
205            )
206        })?;
207        let ops = self.git_branch_ops.as_ref().ok_or_else(|| {
208            EngineError::Mem("git-branch ops are not wired on this engine".to_string())
209        })?;
210        (ops.write_schema)(&gitdir, name, version, files).map_err(EngineError::Backend)?;
211        Ok(())
212    }
213
214    /// Validate a schema package's files before they are sealed. Runs
215    /// the full loader (structural + semantic) plus the section-heading
216    /// round-trip gate, and checks the manifest's declared identity
217    /// matches the `(name, version)` the package is being installed
218    /// under — a mismatch would seal the schema under a ref its own
219    /// manifest contradicts.
220    ///
221    /// `pub` so the below-boot install path (memstead-git-branch's
222    /// repair surface) runs the SAME gate as this booted path — the
223    /// two must never fork into separate validation regimes.
224    pub fn validate_schema_package(
225        name: &str,
226        version: &str,
227        files: &[(String, Vec<u8>)],
228    ) -> Result<(), EngineError> {
229        let invalid = |message: String| EngineError::SchemaPackageInvalid {
230            name: name.to_string(),
231            version: version.to_string(),
232            message,
233        };
234        let manifest_yaml = files
235            .iter()
236            .find(|(rel, _)| rel == "schema.yaml")
237            .map(|(_, bytes)| String::from_utf8_lossy(bytes).into_owned())
238            .ok_or_else(|| invalid("package has no schema.yaml".to_string()))?;
239        let types: Vec<(String, String)> = files
240            .iter()
241            .filter_map(|(rel, bytes)| {
242                rel.strip_prefix("types/")
243                    .and_then(|f| f.strip_suffix(".yaml"))
244                    .map(|stem| {
245                        (
246                            stem.to_string(),
247                            String::from_utf8_lossy(bytes).into_owned(),
248                        )
249                    })
250            })
251            .collect();
252        // Install validates the CURRENT language (the author acts
253        // now) — the retired `optional:` key refuses here, and absent
254        // required keys mean optional.
255        let schema = memstead_schema::load_schema_from_memory_with_format(
256            &manifest_yaml,
257            &types,
258            memstead_schema::loader::MetadataPolarityFormat::RequiredOptIn,
259        )
260        .map_err(|e| invalid(e.to_string()))?;
261        memstead_schema::check_section_heading_roundtrip(&schema)
262            .map_err(|e| invalid(e.to_string()))?;
263        memstead_schema::check_reserved_metadata_keys(&schema)
264            .map_err(|e| invalid(e.to_string()))?;
265        memstead_schema::check_section_formats(&schema).map_err(|e| invalid(e.to_string()))?;
266        let (declared_name, declared_version) =
267            (schema.manifest.name.as_str(), schema.version.to_string());
268        if declared_name != name || declared_version != version {
269            return Err(invalid(format!(
270                "manifest declares '{declared_name}@{declared_version}' but the package is \
271                 being installed as '{name}@{version}'"
272            )));
273        }
274        Self::validate_schema_exemplars(&std::sync::Arc::new(schema)).map_err(invalid)?;
275        Ok(())
276    }
277
278    /// Validate every type exemplar a schema carries by running it
279    /// through the REAL create validation stage:
280    /// an in-memory engine is booted with the candidate schema pinned
281    /// on a virtual mem, and each exemplar is submitted as a
282    /// `dry_run` create — the same gates a real write runs (sections,
283    /// metadata + enums, rel-type vocabulary, edge shape, description
284    /// posture), commit-free by construction. Placeholder relation
285    /// targets are bare slugs scoped to the virtual mem, so target
286    /// existence is never checked (an absent target is the legal
287    /// would-be-stub path).
288    ///
289    /// Returns the defect as a message naming the type — the caller
290    /// wraps it in its own typed envelope (`SchemaPackageInvalid` on
291    /// the install path). There is deliberately no warn-and-carry
292    /// mode: a non-conformant exemplar refuses, because the whole
293    /// value of an exemplar is the impossibility of drift.
294    ///
295    /// `pub` so the built-in suite gates every shipped exemplar
296    /// through the SAME validator (a broken built-in exemplar fails
297    /// CI), and the below-boot install path shares the gate via
298    /// [`Self::validate_schema_package`].
299    pub fn validate_schema_exemplars(
300        schema: &std::sync::Arc<memstead_schema::Schema>,
301    ) -> Result<(), String> {
302        let with_exemplars: Vec<&str> = schema
303            .manifest
304            .types
305            .iter()
306            .filter(|t| {
307                schema
308                    .types
309                    .get(t.as_str())
310                    .is_some_and(|td| td.exemplar.is_some())
311            })
312            .map(String::as_str)
313            .collect();
314        if with_exemplars.is_empty() {
315            return Ok(());
316        }
317
318        let (name, version) = schema.id();
319        let mem = "exemplar";
320        let mount = crate::workspace::Mount {
321            mem: mem.to_string(),
322            schema: Some(memstead_schema::SchemaRef::new(name, version)),
323            storage: crate::workspace::MountStorage::InMemory,
324            capability: crate::workspace::MountCapability::Write,
325            lifecycle: crate::workspace::MountLifecycle::Eager,
326            cross_linkable: true,
327            migration_target: None,
328        };
329        let backend = Box::new(crate::storage::InMemoryBackend::new()) as Box<dyn MemBackend>;
330        let mut engine = Engine::from_mounts_with_schemas_dir_and_extra(
331            vec![(mount, backend)],
332            None,
333            vec![schema.clone()],
334        )
335        .map_err(|e| format!("exemplar validation could not boot: {e}"))?;
336
337        for type_name in with_exemplars {
338            let td = schema
339                .types
340                .get(type_name)
341                .expect("filtered on presence above");
342            let ex = td.exemplar.as_ref().expect("filtered on presence above");
343            let mut relations = Vec::with_capacity(ex.relations.len());
344            for r in &ex.relations {
345                let target = r.target_slug();
346                if target.contains("--") || target.trim().is_empty() {
347                    return Err(format!(
348                        "type '{type_name}' exemplar relation target '{target}' must be a bare \
349                         placeholder slug (no `--`, non-empty) — exemplars live outside \
350                         any mem",
351                    ));
352                }
353                relations.push(crate::ops::RelateArg {
354                    target: crate::entity::EntityId::new(mem, target),
355                    rel_type: r.rel_type_name().to_string(),
356                    description: r.description.clone(),
357                });
358            }
359            let args = crate::engine::CreateEntityArgs {
360                anchors: Vec::new(),
361                mem: mem.to_string(),
362                title: ex.title.clone(),
363                entity_type: type_name.to_string(),
364                sections: ex.sections.clone(),
365                metadata: ex.metadata.clone(),
366                relations,
367                dry_run: true,
368            };
369            if let Err(e) = engine.create_entity(args, crate::vcs::Actor::Cli, None, None) {
370                return Err(format!(
371                    "type '{type_name}' exemplar does not conform: [{}] {e}",
372                    e.code()
373                ));
374            }
375        }
376        Ok(())
377    }
378}