memstead_base/engine/lifecycle.rs
1//! Engine lifecycle — settings/workspace-root setters, runtime
2//! mem add/remove, reload, and export.
3//!
4//! `register_writable_mem` / `unregister_writable_mem` are the
5//! engine-level primitives the `memstead_mem_create` / `memstead_mem_delete`
6//! handlers build on. `reload_one_mem*` re-reads a mount's backend
7//! and refreshes the in-memory store; `reload_each_writable_mem*`
8//! sweeps every writable mount. `export_markdown` regenerates entity
9//! markdown for folder mounts; `export_mem` produces a portable
10//! `.mem` archive via the backend-aware dispatch in
11//! [`crate::ops::export`].
12
13use std::cell::OnceCell;
14use std::collections::HashMap;
15use std::path::PathBuf;
16use std::sync::Arc;
17
18use crate::backend::{BackendError, MemBackend};
19use crate::engine_fallback_type;
20use crate::entity::EntityId;
21use crate::entity::generator::generate_markdown;
22use crate::entity::loader::parse_entries;
23use crate::entity::store_builder::push_entities_into_store;
24use crate::mem::MemOrigin;
25use crate::ops::WarningHint;
26use crate::workspace::{Mount, MountStorage, WorkspaceSettings};
27
28use super::boot::collect_source_entries;
29use super::{BackendFactory, Engine, EngineError, GitBranchOps, MountedBackend};
30
31/// What [`Engine::stage_sealed_schema`] did.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum SchemaStaging {
34 /// The pin already resolves in this workspace — nothing written.
35 /// Re-installing a mem, and installing a second mem that pins the
36 /// same schema, both land here.
37 AlreadyResolvable,
38 /// The package was written into the workspace's local schema
39 /// storage and is resolvable in this process from now on.
40 Staged,
41 /// The archive carries no embedded schema tree. Nothing to stage;
42 /// the pin must resolve on its own or the mount refuses.
43 NoEmbeddedSchema,
44 /// The workspace has no sealed-package storage (a folder-shaped
45 /// workspace: its `.memstead/schemas/` is the authoring tier and
46 /// never holds a third party's sealed bytes). The package was read
47 /// and checked against the pin, nothing was written, and the mount
48 /// resolves its vocabulary from the archive itself — on this shape
49 /// the archive IS the schema storage.
50 CarriedByArchive,
51}
52
53impl Engine {
54 /// Replace the workspace-level settings. Called by
55 /// [`Self::from_workspace_root`] (and the full counterpart) after
56 /// reading `.memstead/workspace.toml`. Tests / direct callers leave
57 /// the default empty value in place. Cheap clone — settings
58 /// carry only data shapes (raw rule lists, link policy map),
59 /// no compiled matchers. Invalidates the lazy
60 /// `create_rule_set_memo` so the next synthesis call rebuilds
61 /// from the new policy.
62 pub fn set_settings(&mut self, settings: WorkspaceSettings) {
63 self.settings = settings;
64 self.create_rule_set_memo = OnceCell::new();
65 }
66
67 /// Replace the backend factory. Full consumers call this once at boot
68 /// (`engine_from_workspace_root`) to install
69 /// `memstead_git_branch::storage::instantiate_full_backend` so the engine
70 /// can materialise git-branch backends on top of folder + archive.
71 /// Consumers without the git-branch crate leave the default in place.
72 pub fn set_backend_factory(&mut self, factory: BackendFactory) {
73 self.backend_factory = factory;
74 }
75
76 /// Insert into the engine's schema map, bumping the schemas epoch
77 /// (the second half of the derived-memo key):
78 /// derived structures depend on schemas, so any change here must
79 /// be visible to the memo-invalidation hooks even when the store
80 /// generation did not move.
81 pub(crate) fn schemas_insert(
82 &mut self,
83 mem: String,
84 schema: std::sync::Arc<memstead_schema::Schema>,
85 ) {
86 self.schemas_epoch += 1;
87 self.schemas.insert(mem, schema);
88 }
89
90 /// Remove from the engine's schema map, bumping the schemas epoch
91 /// — see [`Self::schemas_insert`].
92 pub(crate) fn schemas_remove(&mut self, mem: &str) {
93 self.schemas_epoch += 1;
94 self.schemas.remove(mem);
95 }
96
97 /// Install the unmounted-mem storage discovery hook. Full boot
98 /// sets it; without one, writes referencing
99 /// unmounted mems keep the forward-reference mechanic unchanged.
100 pub fn set_unmounted_storage_prober(&mut self, prober: super::UnmountedStorageProber) {
101 self.unmounted_storage_prober = Some(prober);
102 }
103
104 /// Replace the mutation-timestamp clock — the source every
105 /// engine-stamped metadata field (`init_timestamp` /
106 /// `auto_timestamp` schema flags: `created_date`, `last_modified`)
107 /// reads. A testing affordance for suites that assert over
108 /// canonical entity bytes (e.g. cross-surface hash parity):
109 /// pin both engines to the same constant and byte-level
110 /// nondeterminism from wall-clock seconds disappears. Production
111 /// code never calls this — the default installed at construction
112 /// is the system clock, and the stamped format is unchanged
113 /// either way.
114 pub fn set_mutation_clock(&mut self, clock: crate::engine::MutationClock) {
115 self.mutation_clock = clock;
116 }
117
118 /// Set the caller-declared role for subsequent mutations.
119 /// The surface calls this before every
120 /// mutation with the per-call parameter resolved against its
121 /// session default (per-call wins); `Role::Unspecified` records
122 /// as absence.
123 pub fn set_role(&mut self, role: crate::vcs::Role) {
124 self.current_role = role;
125 }
126
127 /// The currently declared role — what the next mutation records.
128 pub fn current_role(&self) -> crate::vcs::Role {
129 self.current_role
130 }
131
132 /// Set the caller-declared identity for subsequent mutations and
133 /// checks. The surface calls this before
134 /// every operation with the per-call parameter resolved against
135 /// its session default (per-call wins); `None` records as
136 /// absence. Callers pass an already-normalised value
137 /// ([`crate::vcs::normalise_identity`]).
138 pub fn set_identity(&mut self, identity: Option<String>) {
139 self.current_identity = identity;
140 }
141
142 /// Set the transport's actor for the commits this session causes
143 /// without a per-call actor (config writes, sync-state stamps, the
144 /// anchor writers). The CLI sets `Cli` at boot; the MCP server
145 /// sets `Agent`.
146 pub fn set_actor(&mut self, actor: crate::vcs::Actor) {
147 self.current_actor = actor;
148 }
149
150 /// The transport's actor (see [`Self::set_actor`]).
151 pub fn current_actor(&self) -> crate::vcs::Actor {
152 self.current_actor
153 }
154
155 /// Set the transport's client id, when it has one (the MCP client
156 /// after `initialize`; the CLI's own id).
157 pub fn set_client(&mut self, client: Option<crate::vcs::ClientId>) {
158 self.current_client = client;
159 }
160
161 /// The transport's client id (see [`Self::set_client`]).
162 pub fn current_client(&self) -> Option<&crate::vcs::ClientId> {
163 self.current_client.as_ref()
164 }
165
166 /// The commit context of one mutation: its tool, actor, client and
167 /// note, with the session's declared role and identity. Every
168 /// commit the engine writes is built through here (or through
169 /// [`Self::session_commit_context`]), so no path can drop a trailer.
170 pub fn commit_context<'a>(
171 &self,
172 tool: Option<&'a str>,
173 actor: crate::vcs::Actor,
174 client: Option<crate::vcs::ClientId>,
175 note: Option<String>,
176 ) -> crate::vcs::CommitContext<'a> {
177 crate::vcs::CommitContext::new(
178 tool,
179 actor,
180 client,
181 note,
182 self.current_role,
183 self.current_identity.clone(),
184 )
185 }
186
187 /// The commit context of a mutation the session causes as itself:
188 /// the transport's actor and client (see [`Self::set_actor`] and
189 /// [`Self::set_client`]) with the session's role and identity.
190 pub fn session_commit_context<'a>(
191 &self,
192 tool: Option<&'a str>,
193 note: Option<String>,
194 ) -> crate::vcs::CommitContext<'a> {
195 self.commit_context(tool, self.current_actor, self.current_client.clone(), note)
196 }
197
198 /// The currently declared identity — what the next mutation or
199 /// check records.
200 pub fn current_identity(&self) -> Option<&str> {
201 self.current_identity.as_deref()
202 }
203
204 /// Current mutation timestamp as the second-granularity ISO form
205 /// the stamping paths write. Reads [`Self::mutation_clock`] — the
206 /// system clock unless a test pinned it.
207 pub(crate) fn now_iso(&self) -> String {
208 crate::engine::mutation::iso_from_system_time((self.mutation_clock)())
209 }
210
211 /// Install the git-branch ops bundle. Full boot
212 /// (`memstead_git_branch::engine_from_workspace_root`) calls this once
213 /// at construction. Consumers without the git-branch crate leave it unset
214 /// and the git-branch dispatch branches collapse to typed errors / empty
215 /// reports; such an engine serves no git-branch mounts.
216 pub fn set_git_branch_ops(&mut self, ops: GitBranchOps) {
217 self.git_branch_ops = Some(ops);
218 }
219}
220
221// -------------------------------------------------------------------------
222// Cut by phase. Each child opens its own `impl Engine` block, so every
223// method keeps its name, signature and visibility and no consumer moves.
224// -------------------------------------------------------------------------
225
226mod export;
227mod mem_settings;
228mod mounts;
229mod reload;
230mod schema;
231mod schema_pin;
232
233pub use schema_pin::*;
234
235#[cfg(test)]
236mod tests;