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 // Every backend this engine serves waits for its mem's write
66 // lock, in a load and in a direct read, no longer than the
67 // workspace's deadline as it stands now.
68 let limit = self.settings.mutations.write_lock_timeout();
69 for mount in &self.mounts {
70 mount.backend.set_lock_wait(limit);
71 }
72 }
73
74 /// Replace the backend factory. Full consumers call this once at boot
75 /// (`engine_from_workspace_root`) to install
76 /// `memstead_git_branch::storage::instantiate_full_backend` so the engine
77 /// can materialise git-branch backends on top of folder + archive.
78 /// Consumers without the git-branch crate leave the default in place.
79 pub fn set_backend_factory(&mut self, factory: BackendFactory) {
80 self.backend_factory = factory;
81 }
82
83 /// Insert into the engine's schema map, bumping the schemas epoch
84 /// (the second half of the derived-memo key):
85 /// derived structures depend on schemas, so any change here must
86 /// be visible to the memo-invalidation hooks even when the store
87 /// generation did not move.
88 pub(crate) fn schemas_insert(
89 &mut self,
90 mem: String,
91 schema: std::sync::Arc<memstead_schema::Schema>,
92 ) {
93 self.schemas_epoch += 1;
94 self.schemas.insert(mem, schema);
95 }
96
97 /// Remove from the engine's schema map, bumping the schemas epoch
98 /// — see [`Self::schemas_insert`].
99 pub(crate) fn schemas_remove(&mut self, mem: &str) {
100 self.schemas_epoch += 1;
101 self.schemas.remove(mem);
102 }
103
104 /// Install the unmounted-mem storage discovery hook. Full boot
105 /// sets it; without one, writes referencing
106 /// unmounted mems keep the forward-reference mechanic unchanged.
107 pub fn set_unmounted_storage_prober(&mut self, prober: super::UnmountedStorageProber) {
108 self.unmounted_storage_prober = Some(prober);
109 }
110
111 /// Replace the mutation-timestamp clock — the source every
112 /// engine-stamped metadata field (`init_timestamp` /
113 /// `auto_timestamp` schema flags: `created_date`, `last_modified`)
114 /// reads. A testing affordance for suites that assert over
115 /// canonical entity bytes (e.g. cross-surface hash parity):
116 /// pin both engines to the same constant and byte-level
117 /// nondeterminism from wall-clock seconds disappears. Production
118 /// code never calls this — the default installed at construction
119 /// is the system clock, and the stamped format is unchanged
120 /// either way.
121 pub fn set_mutation_clock(&mut self, clock: crate::engine::MutationClock) {
122 self.mutation_clock = clock;
123 }
124
125 /// Set the caller-declared role for subsequent mutations.
126 /// The surface calls this before every
127 /// mutation with the per-call parameter resolved against its
128 /// session default (per-call wins); `Role::Unspecified` records
129 /// as absence.
130 pub fn set_role(&mut self, role: crate::vcs::Role) {
131 self.current_role = role;
132 }
133
134 /// The currently declared role — what the next mutation records.
135 pub fn current_role(&self) -> crate::vcs::Role {
136 self.current_role
137 }
138
139 /// Set the caller-declared identity for subsequent mutations and
140 /// checks. The surface calls this before
141 /// every operation with the per-call parameter resolved against
142 /// its session default (per-call wins); `None` records as
143 /// absence. Callers pass an already-normalised value
144 /// ([`crate::vcs::normalise_identity`]).
145 pub fn set_identity(&mut self, identity: Option<String>) {
146 self.current_identity = identity;
147 }
148
149 /// Set the transport's actor for the commits this session causes
150 /// without a per-call actor (config writes, sync-state stamps, the
151 /// anchor writers). The CLI sets `Cli` at boot; the MCP server
152 /// sets `Agent`.
153 pub fn set_actor(&mut self, actor: crate::vcs::Actor) {
154 self.current_actor = actor;
155 }
156
157 /// The transport's actor (see [`Self::set_actor`]).
158 pub fn current_actor(&self) -> crate::vcs::Actor {
159 self.current_actor
160 }
161
162 /// Set the transport's client id, when it has one (the MCP client
163 /// after `initialize`; the CLI's own id).
164 pub fn set_client(&mut self, client: Option<crate::vcs::ClientId>) {
165 self.current_client = client;
166 }
167
168 /// The transport's client id (see [`Self::set_client`]).
169 pub fn current_client(&self) -> Option<&crate::vcs::ClientId> {
170 self.current_client.as_ref()
171 }
172
173 /// The commit context of one mutation: its tool, actor, client and
174 /// note, with the session's declared role and identity. Every
175 /// commit the engine writes is built through here (or through
176 /// [`Self::session_commit_context`]), so no path can drop a trailer.
177 pub fn commit_context<'a>(
178 &self,
179 tool: Option<&'a str>,
180 actor: crate::vcs::Actor,
181 client: Option<crate::vcs::ClientId>,
182 note: Option<String>,
183 ) -> crate::vcs::CommitContext<'a> {
184 crate::vcs::CommitContext::new(
185 tool,
186 actor,
187 client,
188 note,
189 self.current_role,
190 self.current_identity.clone(),
191 )
192 }
193
194 /// The commit context of a mutation the session causes as itself:
195 /// the transport's actor and client (see [`Self::set_actor`] and
196 /// [`Self::set_client`]) with the session's role and identity.
197 pub fn session_commit_context<'a>(
198 &self,
199 tool: Option<&'a str>,
200 note: Option<String>,
201 ) -> crate::vcs::CommitContext<'a> {
202 self.commit_context(tool, self.current_actor, self.current_client.clone(), note)
203 }
204
205 /// The currently declared identity — what the next mutation or
206 /// check records.
207 pub fn current_identity(&self) -> Option<&str> {
208 self.current_identity.as_deref()
209 }
210
211 /// Current mutation timestamp as the second-granularity ISO form
212 /// the stamping paths write. Reads [`Self::mutation_clock`] — the
213 /// system clock unless a test pinned it.
214 pub(crate) fn now_iso(&self) -> String {
215 crate::engine::mutation::iso_from_system_time((self.mutation_clock)())
216 }
217
218 /// Install the git-branch ops bundle. Full boot
219 /// (`memstead_git_branch::engine_from_workspace_root`) calls this once
220 /// at construction. Consumers without the git-branch crate leave it unset
221 /// and the git-branch dispatch branches collapse to typed errors / empty
222 /// reports; such an engine serves no git-branch mounts.
223 pub fn set_git_branch_ops(&mut self, ops: GitBranchOps) {
224 self.git_branch_ops = Some(ops);
225 }
226}
227
228// -------------------------------------------------------------------------
229// Cut by phase. Each child opens its own `impl Engine` block, so every
230// method keeps its name, signature and visibility and no consumer moves.
231// -------------------------------------------------------------------------
232
233mod export;
234mod mem_settings;
235mod mounts;
236mod reload;
237mod schema;
238mod schema_pin;
239
240pub use schema_pin::*;
241
242#[cfg(test)]
243mod tests;