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    /// The gitdir that holds sealed third-party packages (the
155    /// `__MEMSTEAD:schemas/` ref): the first git-branch mount's, else the
156    /// workspace's `mem-repo/.git`. `None` on a folder-shaped workspace,
157    /// whose `.memstead/schemas/` is the authoring tier and never holds
158    /// sealed bytes.
159    fn sealed_schema_gitdir(&self) -> Option<PathBuf> {
160        self.mounts
161            .iter()
162            .find_map(|m| match &m.mount.storage {
163                crate::workspace::MountStorage::GitBranch { gitdir, .. } => Some(gitdir.clone()),
164                _ => None,
165            })
166            .or_else(|| {
167                self.workspace_root()
168                    .map(|r| r.join("mem-repo").join(".git"))
169            })
170            .filter(|g| g.is_dir())
171    }
172
173    /// Write a schema package into the workspace's local schema
174    /// storage — the git-branch `__MEMSTEAD:schemas/` ref when the
175    /// workspace is mem-repo-shaped. Shares
176    /// [`Self::install_schema`]'s gitdir resolution so authored and
177    /// staged packages land in one place.
178    fn write_to_local_schema_source(
179        &self,
180        name: &str,
181        version: &str,
182        files: &[(String, Vec<u8>)],
183    ) -> Result<(), EngineError> {
184        let gitdir = self.sealed_schema_gitdir().ok_or_else(|| {
185            EngineError::Mem(
186                "staging a schema requires a mem-repo workspace — the folder workspace's \
187                     `.memstead/schemas/` is the authoring tier and never holds sealed \
188                     third-party packages"
189                    .to_string(),
190            )
191        })?;
192        let ops = self.git_branch_ops.as_ref().ok_or_else(|| {
193            EngineError::Mem("git-branch ops are not wired on this engine".to_string())
194        })?;
195        (ops.write_schema)(&gitdir, name, version, files).map_err(EngineError::Backend)?;
196        Ok(())
197    }
198
199    /// Validate a schema package's files before they are sealed. Runs
200    /// the full loader (structural + semantic) plus the section-heading
201    /// round-trip gate, and checks the manifest's declared identity
202    /// matches the `(name, version)` the package is being installed
203    /// under — a mismatch would seal the schema under a ref its own
204    /// manifest contradicts.
205    ///
206    /// `pub` so the below-boot install path (memstead-git-branch's
207    /// repair surface) runs the SAME gate as this booted path — the
208    /// two must never fork into separate validation regimes.
209    pub fn validate_schema_package(
210        name: &str,
211        version: &str,
212        files: &[(String, Vec<u8>)],
213    ) -> Result<(), EngineError> {
214        let invalid = |message: String| EngineError::SchemaPackageInvalid {
215            name: name.to_string(),
216            version: version.to_string(),
217            message,
218        };
219        let manifest_yaml = files
220            .iter()
221            .find(|(rel, _)| rel == "schema.yaml")
222            .map(|(_, bytes)| String::from_utf8_lossy(bytes).into_owned())
223            .ok_or_else(|| invalid("package has no schema.yaml".to_string()))?;
224        let types: Vec<(String, String)> = files
225            .iter()
226            .filter_map(|(rel, bytes)| {
227                rel.strip_prefix("types/")
228                    .and_then(|f| f.strip_suffix(".yaml"))
229                    .map(|stem| {
230                        (
231                            stem.to_string(),
232                            String::from_utf8_lossy(bytes).into_owned(),
233                        )
234                    })
235            })
236            .collect();
237        // Install validates the CURRENT language (the author acts
238        // now) — the retired `optional:` key refuses here, and absent
239        // required keys mean optional.
240        let schema = memstead_schema::load_schema_from_memory_with_format(
241            &manifest_yaml,
242            &types,
243            memstead_schema::loader::MetadataPolarityFormat::RequiredOptIn,
244        )
245        .map_err(|e| invalid(e.to_string()))?;
246        memstead_schema::check_section_heading_roundtrip(&schema)
247            .map_err(|e| invalid(e.to_string()))?;
248        memstead_schema::check_reserved_metadata_keys(&schema)
249            .map_err(|e| invalid(e.to_string()))?;
250        memstead_schema::check_section_formats(&schema).map_err(|e| invalid(e.to_string()))?;
251        let (declared_name, declared_version) =
252            (schema.manifest.name.as_str(), schema.version.to_string());
253        if declared_name != name || declared_version != version {
254            return Err(invalid(format!(
255                "manifest declares '{declared_name}@{declared_version}' but the package is \
256                 being installed as '{name}@{version}'"
257            )));
258        }
259        Self::validate_schema_exemplars(&std::sync::Arc::new(schema)).map_err(invalid)?;
260        Ok(())
261    }
262
263    /// Validate every type exemplar a schema carries by running it
264    /// through the REAL create validation stage:
265    /// an in-memory engine is booted with the candidate schema pinned
266    /// on a virtual mem, and each exemplar is submitted as a
267    /// `dry_run` create — the same gates a real write runs (sections,
268    /// metadata + enums, rel-type vocabulary, edge shape, description
269    /// posture), commit-free by construction. Placeholder relation
270    /// targets are bare slugs scoped to the virtual mem, so target
271    /// existence is never checked (an absent target is the legal
272    /// would-be-stub path).
273    ///
274    /// Returns the defect as a message naming the type — the caller
275    /// wraps it in its own typed envelope (`SchemaPackageInvalid` on
276    /// the install path). There is deliberately no warn-and-carry
277    /// mode: a non-conformant exemplar refuses, because the whole
278    /// value of an exemplar is the impossibility of drift.
279    ///
280    /// `pub` so the built-in suite gates every shipped exemplar
281    /// through the SAME validator (a broken built-in exemplar fails
282    /// CI), and the below-boot install path shares the gate via
283    /// [`Self::validate_schema_package`].
284    pub fn validate_schema_exemplars(
285        schema: &std::sync::Arc<memstead_schema::Schema>,
286    ) -> Result<(), String> {
287        let with_exemplars: Vec<&str> = schema
288            .manifest
289            .types
290            .iter()
291            .filter(|t| {
292                schema
293                    .types
294                    .get(t.as_str())
295                    .is_some_and(|td| td.exemplar.is_some())
296            })
297            .map(String::as_str)
298            .collect();
299        if with_exemplars.is_empty() {
300            return Ok(());
301        }
302
303        let (name, version) = schema.id();
304        let mem = "exemplar";
305        let mount = crate::workspace::Mount {
306            mem: mem.to_string(),
307            schema: Some(memstead_schema::SchemaRef::new(name, version)),
308            storage: crate::workspace::MountStorage::InMemory,
309            capability: crate::workspace::MountCapability::Write,
310            lifecycle: crate::workspace::MountLifecycle::Eager,
311            cross_linkable: true,
312            migration_target: None,
313        };
314        let backend = Box::new(crate::storage::InMemoryBackend::new()) as Box<dyn MemBackend>;
315        let mut engine = Engine::from_mounts_with_schemas_dir_and_extra(
316            vec![(mount, backend)],
317            None,
318            vec![schema.clone()],
319        )
320        .map_err(|e| format!("exemplar validation could not boot: {e}"))?;
321
322        for type_name in with_exemplars {
323            let td = schema
324                .types
325                .get(type_name)
326                .expect("filtered on presence above");
327            let ex = td.exemplar.as_ref().expect("filtered on presence above");
328            let mut relations = Vec::with_capacity(ex.relations.len());
329            for r in &ex.relations {
330                let target = r.target_slug();
331                if target.contains("--") || target.trim().is_empty() {
332                    return Err(format!(
333                        "type '{type_name}' exemplar relation target '{target}' must be a bare \
334                         placeholder slug (no `--`, non-empty) — exemplars live outside \
335                         any mem",
336                    ));
337                }
338                relations.push(crate::ops::RelateArg {
339                    target: crate::entity::EntityId::new(mem, target),
340                    rel_type: r.rel_type_name().to_string(),
341                    description: r.description.clone(),
342                });
343            }
344            let args = crate::engine::CreateEntityArgs {
345                anchors: Vec::new(),
346                mem: mem.to_string(),
347                title: ex.title.clone(),
348                entity_type: type_name.to_string(),
349                sections: ex.sections.clone(),
350                metadata: ex.metadata.clone(),
351                relations,
352                dry_run: true,
353            };
354            if let Err(e) = engine.create_entity(args, crate::vcs::Actor::Cli, None, None) {
355                return Err(format!(
356                    "type '{type_name}' exemplar does not conform: [{}] {e}",
357                    e.code()
358                ));
359            }
360        }
361        Ok(())
362    }
363}