memstead_base/engine/mod.rs
1//! Unified engine.
2//!
3//! **One [`Engine`] type, three storage backends**: the engine sits
4//! above [`MemBackend`] and routes reads / writes to the backend
5//! named by each mount's mem. Consumers reach the engine through
6//! [`Engine::from_workspace_root`] (folder + archive backends) or
7//! `memstead_git_branch::engine_from_workspace_root` (adds git-branch).
8//!
9//! ## Routing
10//!
11//! Each mount holds one mem. Lookup is by mem name: the first
12//! mount whose `mem` field equals the requested name wins. One mount
13//! per mem is enforced — duplicates are a configuration bug, not a
14//! feature, and the constructor rejects them.
15
16use std::cell::OnceCell;
17use std::collections::HashMap;
18use std::path::{Path, PathBuf};
19use std::sync::Arc;
20
21use memstead_schema::Schema;
22
23use crate::backend::{BackendError, MemBackend};
24use crate::graph::LouvainOutput;
25use crate::mem::MemRouterSnapshot;
26use crate::ops::WarningHint;
27#[cfg(not(target_arch = "wasm32"))]
28use crate::search_index::MemIndex;
29use crate::store::Store;
30use crate::workspace::{Mount, WorkspaceSettings};
31
32pub mod apply_commit;
33pub mod archive;
34pub mod boot;
35pub mod check_ops;
36pub mod checks_transport;
37pub mod conflicts;
38pub mod drift;
39pub mod due;
40pub mod error;
41pub mod events;
42pub mod export_html;
43pub mod export_llms_txt;
44pub mod gates;
45pub mod history;
46pub mod independence;
47pub mod lifecycle;
48pub mod mutation;
49pub mod outcomes;
50pub mod proposal;
51pub mod query;
52pub mod review;
53pub mod roster;
54
55pub use archive::FromArchiveBytesError;
56pub use error::{
57 BootError, EngineError, INLINE_LIST_CAP, MissingWikiLink, ReferrerInfo, SchemaSourceDiagnostic,
58 format_inline_list_overflow,
59};
60#[cfg(feature = "tokio")]
61pub use events::DEFAULT_BROADCAST_CAPACITY;
62pub use events::{EventCallback, MemChangedEvent, SubscriptionHandle};
63pub use history::{
64 EntityHistoryReport, EntityTouch, HISTORY_PAGE_DEFAULT, HISTORY_PAGE_MAX, StoryStart,
65};
66pub use mutation::delete::DeleteReferrers;
67pub use mutation::{PATCH_OLD_NOT_FOUND_CONTENT_CAP, RELATIONSHIP_CYCLE_PATH_CAP};
68pub use outcomes::{
69 CreateEntityArgs, CreateEntityOutcome, DeleteEntityArgs, DeleteEntityOutcome, RelateAction,
70 RelateEntityArgs, RelateEntityOutcome, RenameEntityArgs, RenameEntityOutcome, RetypeEdge,
71 RetypeEdgeDirection, RetypeEntityArgs, RetypeEntityOutcome, RetypeProblem, SetSchemaOutcome,
72 SetSchemaResult, UpdateEntityArgs, UpdateEntityOutcome,
73};
74pub use review::{ReviewMarkStatus, SetReviewMarkOutcome};
75
76pub use boot::{SchemaResolver, load_workspace_schemas, resolve_builtin_schema_pin_pub};
77pub use lifecycle::SchemaStaging;
78
79/// One mem attachment, paired with the backend that serves it.
80/// Constructed by [`Engine::from_mounts`] and held internally.
81/// `pub(crate)` only so the crate-internal `boot::build_mem_router_from_mounts`
82/// can name it in its signature — never re-exported.
83pub(crate) struct MountedBackend {
84 mount: Mount,
85 backend: Box<dyn MemBackend>,
86 /// Last cursor returned by `backend.current_head()`. Seeded in
87 /// [`Engine::from_mounts`]; refreshed by
88 /// [`Engine::reload_if_stale`] after a successful reload.
89 /// `None` means the backend doesn't track a head (folder /
90 /// archive) — drift detection is a no-op for this mount.
91 last_known_head: Option<String>,
92 /// Per-mem `.memstead/config.json` payload — surfaces via
93 /// [`Engine::mem_config_for`] for handlers that need
94 /// `write_guidance` / `extra` (`memstead_health
95 /// { include_config: true }`'s per-mem detail block).
96 ///
97 /// Read at construction through the backend's `read_mem_config`,
98 /// whatever the storage kind (folder: `<path>/.memstead/config.json`;
99 /// archive: the zip member; git-branch: the metadata branch's
100 /// `mems/<leaf>/config.json`). `None` when the backend has no config
101 /// or the payload does not parse.
102 mem_config: Option<memstead_schema::config::MemConfig>,
103 /// Per-mem authoring-provenance payload read from the archive's
104 /// `.memstead/provenance.json` at construction (via
105 /// [`crate::backend::MemBackend::read_archive_provenance`]). `None`
106 /// when the backend carries no provenance member (a pre-provenance
107 /// archive, or a backend that does not surface one) — surfaced as
108 /// provenance-absent via [`Engine::archive_provenance_for`]. A
109 /// malformed payload is downgraded to `None` rather than failing the
110 /// mount: the member is additive.
111 archive_provenance: Option<memstead_schema::ArchiveProvenance>,
112 /// The sealed check records an archive mount carries
113 /// (`.memstead/checks.json`), read at construction via
114 /// [`crate::backend::MemBackend::read_archive_checks`]. `None` on
115 /// every writable mount (their check state is the workspace
116 /// ledger's) and on an archive sealed without records; every
117 /// check-state read on an archive mount derives from this and never
118 /// from a workspace ledger ([`Engine::archive_checks_for`]).
119 archive_checks: Option<crate::check::SealedChecks>,
120 /// `true` while a [`MountLifecycle::Lazy`] mount's entities have not
121 /// been loaded into the store — the mount's metadata half (config,
122 /// schema pin, provenance) is resolved at boot, the entity load is
123 /// deferred to the first operation that needs the mem
124 /// ([`Engine::ensure_mems_loaded`]). Always `false` for eager
125 /// mounts, and permanently `false` once the deferred load lands.
126 /// A deferred mem is never absent: it stays on the mount roster
127 /// with its schema resolved, and every read surface either triggers
128 /// the load or reports the state — silence is the one forbidden
129 /// rendering.
130 ///
131 /// [`MountLifecycle::Lazy`]: crate::workspace::MountLifecycle::Lazy
132 deferred: bool,
133}
134
135/// One quarantined mem: the mem-level boot failure that took it out of
136/// service, and the retained mount record `reload` uses to re-attempt
137/// the attach after a repair. The reason code/message are plan-01
138/// typed material — the message's final clause names the repair
139/// command, so the roster entry is actionable as-is.
140#[derive(Debug, Clone)]
141pub struct QuarantinedMem {
142 /// The mount that failed to attach, retained verbatim for reload.
143 pub mount: crate::workspace::Mount,
144 /// Typed code of the underlying failure (e.g. `SCHEMA_NOT_FOUND`,
145 /// `MEM_CONFIG_INCOMPLETE`, `MEM_ERROR`).
146 pub reason_code: String,
147 /// Full message of the underlying failure, repair command
148 /// included.
149 pub reason_message: String,
150}
151
152/// Unified engine. Holds a list of mounted backends and routes
153/// mem-named operations to the right one.
154///
155/// `Send` so the engine can sit behind a `Mutex` (today's pattern
156/// in the MCP server). The trait object's `Send + Sync` bound on
157/// `MemBackend` keeps the inner backends thread-safe; the engine
158/// itself is single-threaded by design (the lazy memos are
159/// `OnceCell`, which is `!Sync`).
160///
161/// `Debug` is hand-written to avoid requiring `Debug` on the
162/// `dyn MemBackend` trait object — backend impls are free to
163/// stay non-`Debug`.
164///
165/// ## Load-on-init
166///
167/// `Engine::from_mounts` walks each backend at construction time
168/// (`list_entities` + `read_entity` + parse) and populates a single
169/// shared [`Store`] with entities and edges from every mount. Each
170/// mount's schema resolves from its own pin (the backend config's
171/// schema, or the mount-record assertion as fallback) through the
172/// `SchemaResolver`, so `schemas` holds genuinely heterogeneous
173/// schemas in a multi-schema workspace. Per-file errors don't fail
174/// construction; they collect into [`Engine::load_errors`] for the
175/// operator to inspect.
176pub struct Engine {
177 mounts: Vec<MountedBackend>,
178 store: Store,
179 schemas: HashMap<String, Arc<Schema>>,
180 /// Workspace-authored schemas loaded from
181 /// `WorkspaceSettings.schemas_dir` at construction. Distinct from
182 /// `schemas` (per-mem, only schemas pinned by a mount): this
183 /// catalogue carries every workspace-loaded schema regardless of
184 /// whether a mem pins it. Surfaced via
185 /// [`Self::workspace_schemas`] for handlers that need to enumerate
186 /// schemas referenced by `mem_create_rules.schemas[]` but not
187 /// pinned by any mem — `memstead_overview` lists them in `## Schemas`
188 /// so an agent sees what could be pinned. Empty when no
189 /// `schemas_dir` was passed.
190 workspace_schemas: Vec<Arc<Schema>>,
191 /// Embedded built-in schemas loaded once at boot from
192 /// `memstead_schema::builtins::load_builtin_schemas()`. The boot path
193 /// uses this catalogue to resolve each mount's schema pin; storing
194 /// it on the engine lets read handlers (MCP's `memstead_schema`,
195 /// `memstead_overview`'s `## Schemas` rendering) surface every built-in
196 /// without re-walking the embedded directory. Schemas declared in
197 /// `workspace_schemas` shadow built-ins on `(name, version)`
198 /// collision — handlers walking both lists must check workspace
199 /// first.
200 builtin_schemas: Vec<Arc<Schema>>,
201 load_errors: Vec<(PathBuf, String)>,
202 /// Lazily-computed Louvain community detection across the
203 /// engine-wide store. Populated on first call to
204 /// [`Self::communities`]; invalidated by
205 /// [`Self::invalidate_communities`] which every mutation method
206 /// calls after a successful write. `OnceCell` is `!Sync`; the
207 /// engine is `Send` (it is moved into a `Mutex` by every consumer)
208 /// but not `Sync`.
209 /// Generation-keyed (flywheel W8/01): the memo carries the store
210 /// generation it was computed at; the invalidation hook clears it
211 /// only when the store has actually moved past that generation —
212 /// which is what makes a rolled-back batch (store snapshot
213 /// restored, generation restored with it) keep serving the memo
214 /// its state was computed from, and makes it impossible for the
215 /// rolled-back interim state to be served as fresh.
216 community_memo: OnceCell<(DerivedKey, LouvainOutput)>,
217 /// Grounded-labelling memo — one `MemLabelling` per mem whose
218 /// schema declares `relationships.labelling`, computed on first
219 /// access and invalidated exactly where the community memo is
220 /// (the reset lives inside [`Self::invalidate_communities`], so
221 /// every mutation site, drift reload, quarantine attach/detach
222 /// and apply-commit invalidate both without a second call).
223 /// Generation-keyed like `community_memo`.
224 labelling_memo: OnceCell<(
225 DerivedKey,
226 HashMap<String, crate::ops::labelling::MemLabelling>,
227 )>,
228 /// Lazily-computed per-mem search index map. Built on first call
229 /// to [`Self::search_indexes`] via [`build_all`]; invalidated by
230 /// [`Self::invalidate_search_indexes`] alongside the community
231 /// cache so every mutation triggers a fresh build on the next
232 /// search. Absent on `wasm32` targets — search lives behind the
233 /// bridge (see `EngineError::SearchUnavailable`).
234 #[cfg(not(target_arch = "wasm32"))]
235 /// Generation-keyed like `community_memo`.
236 search_indexes_memo: OnceCell<(DerivedKey, HashMap<String, MemIndex>)>,
237 /// The second half of [`DerivedKey`]: bumped whenever the
238 /// `schemas` map changes (schema switch, mount register/remove).
239 /// Both derived structures depend on schemas as well as the store
240 /// — community weights and the index field set come from the
241 /// pinned schema — so a schema change must invalidate them even
242 /// though the STORE generation did not move (the schema-switch
243 /// staleness the whole-map drop used to mask).
244 schemas_epoch: u64,
245 /// Workspace-level operator policy — mem create/delete rules,
246 /// cross-mem link permissions. Defaults to empty; populated via
247 /// [`Self::set_settings`] when [`Self::from_workspace_root`] (or
248 /// the full counterpart) reads `.memstead/workspace.toml`. Surfaced
249 /// read-only via [`Self::settings`] for MCP handlers and other
250 /// consumers.
251 settings: WorkspaceSettings,
252 /// Lazily-compiled [`crate::mem_management::CreateRuleSet`] over
253 /// `settings.mem_create_rules`. Built on first
254 /// [`Self::cross_mem_link_allowed`] call that needs synthesis;
255 /// invalidated by [`Self::set_settings`] (so a fresh policy
256 /// re-compiles on the next call). Compilation errors are logged
257 /// and the cache stays empty — synthesis is best-effort, the
258 /// resolver falls back to explicit-policy resolution. Operators
259 /// who want hard validation pre-compile via
260 /// [`crate::mem_management::CreateRuleSet::new`] before passing
261 /// settings.
262 create_rule_set_memo: OnceCell<crate::mem_management::CreateRuleSet>,
263 /// Per-mem data-trust origin declared by the embedding deployment
264 /// (e.g. a curated hosted read tier vouching for a read-only mount as
265 /// first-party). A *composition* fact set through
266 /// [`Self::declare_mem_origin`] by the process that owns the engine —
267 /// never persisted with the mem, never derived from mem content, and
268 /// deliberately not reachable over MCP, so a publisher cannot forge
269 /// first-party. Empty by default; [`Self::mem_origin_class`] falls back
270 /// to the writability inference for undeclared mems.
271 declared_origins: HashMap<String, crate::render::OriginClass>,
272 /// The workspace's own writing identities, declared by the embedding
273 /// deployment through [`Self::declare_owner_identities`]. A
274 /// composition fact on the same terms as `declared_origins`: set by
275 /// the process that owns the engine, never persisted with a mem,
276 /// never reachable over MCP, so nothing that can write a mem-repo can
277 /// add itself. It classifies text a party OTHER than the workspace
278 /// authored into workspace state — a check row's method note and
279 /// finding message, written by whatever agent the owner pointed at
280 /// the ledger, under an identity the launching side assigned.
281 ///
282 /// Empty by default, and empty means undeclared: every ledger
283 /// identity then inherits its mem's class, which is what the engine
284 /// did before this field, so an existing deployment is byte-identical.
285 /// A declared set makes an identity outside it third-party; a row with
286 /// no identity at all stays unconfirmable and inherits, never guessed
287 /// third-party (the same reading the independence gate takes).
288 owner_identities: std::collections::BTreeSet<String>,
289 /// Lazy per-mem map of entities whose claim-carrying sections are a
290 /// contributor's bytes, read from each writable mem's proposal record:
291 /// slug → the mark the merge recorded. Generation-keyed and
292 /// invalidated exactly like `community_memo`, so a merge's own
293 /// invalidation refreshes it. See [`Self::entity_origin_class`].
294 foreign_entities_memo: OnceCell<(DerivedKey, ForeignMarks)>,
295 /// Workspace root path — set when the engine boots from a
296 /// workspace store ([`Self::from_workspace_root`] or the full
297 /// counterpart). `None` for tests + ad-hoc consumers that build
298 /// the engine directly from a mount list. Surfaced via
299 /// [`Self::workspace_root`] for handlers that need filesystem
300 /// context (e.g. [`Self::health`]'s outer-repo .gitignore
301 /// check).
302 workspace_root: Option<PathBuf>,
303 /// The mount roster as this engine last read or last wrote it —
304 /// the baseline [`Engine::persist_state`] diffs against so a state
305 /// write publishes THIS engine's changes without republishing its
306 /// whole cached view over whatever a sibling process has since
307 /// registered. Interior mutability because `persist_state` takes
308 /// `&self`; the engine is already `!Sync`.
309 mounts_baseline: std::cell::RefCell<Vec<crate::workspace::Mount>>,
310 /// Typed warnings surfaced during mem load — drift findings
311 /// like [`WarningHint::SuspiciousNestedPrefix`] and
312 /// [`WarningHint::DuplicateSectionHeading`] that the loader
313 /// pipeline collects per entity. Empty for the V1 unified
314 /// engine; the field is in place so handlers and the health
315 /// surface can include them when the loader pipeline grows the
316 /// warning generators.
317 load_warnings: Vec<WarningHint>,
318 /// Mems that failed their mem-level boot step (unresolvable or
319 /// missing schema pin, backend instantiation or read failure) and
320 /// are quarantined instead of failing the whole workspace —
321 /// degrade, never disappear. A quarantined mem serves NOTHING:
322 /// operations naming it refuse with the typed `MEM_QUARANTINED`
323 /// code carrying the underlying reason (quarantine is not
324 /// tolerance — no partial data from a broken mem). The retained
325 /// [`Mount`] record lets `reload` re-attempt the attach after a
326 /// repair, without a process restart. Surfaced on overview and
327 /// health as the quarantine roster.
328 quarantined: Vec<QuarantinedMem>,
329 /// Workspace-level boot diagnosis carried by a diagnostic-shell
330 /// engine ([`Engine::diagnostic_shell`]): the typed reason the
331 /// REAL workspace could not boot at all (e.g. an unparseable
332 /// workspace store). `None` on every ordinarily booted engine.
333 /// Surfaced on overview and health so a session over a wholly
334 /// unbootable workspace can always ask WHY the graph is gone.
335 boot_diagnosis: Option<(String, String)>,
336 /// Pipeline configs (Medium / Facet / Projection / Ingest) loaded
337 /// from the workspace store at boot. Empty for engines built via
338 /// `from_mounts*` (tests, in-memory consumers) and for any workspace
339 /// that declares no pipelines; the workspace-root boot paths
340 /// (`from_workspace_root` and the full counterpart) populate it via
341 /// [`crate::pipeline_store::load_pipeline_configs`]. Read-only
342 /// runtime surface — exposed through [`Self::pipeline_configs`]; the
343 /// engine neither runs nor schedules pipelines (the ingest skill and
344 /// future consumers do).
345 pipeline_configs: crate::pipeline_store::BindingConfigs,
346 /// Runtime snapshot of writable / visible mems. Derived from
347 /// the mount list at construction: writable mounts
348 /// (`MountCapability::Write`) register via `add_writable` with
349 /// the storage's directory path (folder → `path`, git-branch →
350 /// None, archive shouldn't be writable); read-only mounts
351 /// register via `add_writable` (folder/git-branch) or
352 /// `add_read_only` (archive). Used by MCP handlers that need the
353 /// writable/visible roster + per-mem origin (`memstead_health
354 /// include_config: true`, `memstead_overview`'s mem list,
355 /// `memstead_mem_create`'s collision check).
356 ///
357 /// Wrapped in `Arc` so the COW-snapshot discipline — clone the
358 /// snapshot, mutate the clone, swap the `Arc` — keeps writers
359 /// and concurrent readers from contending on the live mount
360 /// list.
361 mem_router: Arc<MemRouterSnapshot>,
362 /// Backend factory — function pointer used by
363 /// [`crate::mem_management::create_mem`] (and future runtime
364 /// mount-add paths) to materialise a [`MemBackend`] from a
365 /// [`Mount`] declaration. Defaults to
366 /// [`crate::workspace_store::instantiate_local_backend`] so
367 /// folder + archive only consumers work out of the box. Git-branch
368 /// consumers swap in `memstead_git_branch::storage::instantiate_full_backend`
369 /// via [`Self::set_backend_factory`] after constructing the engine —
370 /// `engine_from_workspace_root` does this once at boot. Function
371 /// pointer (not `Box<dyn Fn>`) because the backend factory is
372 /// stateless, `Send + Sync + Copy`, and one less allocation on the
373 /// hot path matters for the multi-mem pattern this engine is
374 /// designed around.
375 backend_factory: BackendFactory,
376 /// Storage discovery for UNMOUNTED mems: set by
377 /// the git-branch boot, `None` in embedded engines (which keep the
378 /// forward-reference mechanic unchanged for unmounted targets).
379 pub(crate) unmounted_storage_prober: Option<UnmountedStorageProber>,
380 /// Git-branch ops bundle — function pointers for the per-mount
381 /// operations whose implementations live in `memstead-git-branch`
382 /// (and therefore can't sit on the `MemBackend` trait without
383 /// inverting the crate dependency). Full boot
384 /// (`memstead_git_branch::engine_from_workspace_root`) installs the
385 /// bundle via [`Self::set_git_branch_ops`]; consumers without it leave
386 /// it `None` and `Engine::changes_since` / `Engine::export_mem`
387 /// fall through to the folder/archive-only branches.
388 git_branch_ops: Option<GitBranchOps>,
389 /// Per-mem subscriber registry for [`MemChangedEvent`]s. Held
390 /// behind `Arc<Mutex<_>>` so [`SubscriptionHandle`]s — which own
391 /// the consumer's view of the subscription lifetime — can call
392 /// back into the registry on `Drop` without a self-reference cycle
393 /// to the engine. The emit path (in `record_self_write`) snapshots
394 /// the per-mem callback list under the lock, releases the lock,
395 /// and then invokes the callbacks — so a callback that re-enters
396 /// the engine for a read does not deadlock against the registry.
397 event_subscribers: Arc<std::sync::Mutex<events::SubscriberRegistry>>,
398 /// Reload-before-operation notices recorded by
399 /// [`Self::reload_if_stale`] when an operation triggered a mem
400 /// reload. Built at reload time — when the backend's current head
401 /// equals the head we reloaded to, *before* any mutation in the
402 /// same operation commits — so the delta describes only the
403 /// sibling's change, never the engine's own follow-on write.
404 /// Reachable only through an [`drift::OperationScope`]: `begin`
405 /// clears, `finish` hands the notices out as a value, and a
406 /// dropped scope clears again, so no operation inherits another's
407 /// notice and nothing on the engine hands them out on demand.
408 pending_mem_changed: Vec<crate::ops::MemChangedNotice>,
409 /// The mount roster as last reconciled (`roster.rs`): `None` until the
410 /// first observation captures the baseline.
411 roster_fingerprint: Option<roster::RosterFingerprint>,
412 /// Subscribers to applied roster changes: `(next id, callbacks)`.
413 roster_subscribers: Arc<roster::RosterSubscribers>,
414 /// Mems that left the roster during this engine's lifetime and have
415 /// not returned — the memory behind the `MEM_UNMOUNTED` refusal.
416 recently_unmounted: std::collections::HashSet<String>,
417 /// Test-only: make the unmount of the named mem fail before it
418 /// touches any state, to prove the roster change stays unapplied.
419 #[cfg(test)]
420 pub(crate) inject_unmount_failure: Option<String>,
421 /// Timestamp source for engine-stamped mutation metadata
422 /// (`created_date` on create, `last_modified` on update/relate/
423 /// rename — every field the schema marks `init_timestamp` /
424 /// `auto_timestamp`). Defaults to the system clock; tests that
425 /// assert over canonical entity bytes pin it via
426 /// [`Self::set_mutation_clock`] so two engines stamp identical
427 /// values. A testability affordance, not a behaviour switch:
428 /// nothing in production swaps the default, and the stamped
429 /// format (second-granularity RFC 3339, see
430 /// `mutation::iso_from_system_time`) is unchanged.
431 mutation_clock: MutationClock,
432 /// The caller-declared role for mutations in this session
433 ///. Set by the surface before each mutation
434 /// (per-call parameter wins over the surface's session default);
435 /// `Unspecified` records as absence. Session state on the engine
436 /// — the `mutation_clock` precedent — so the role travels into
437 /// every commit context and provenance record without widening
438 /// every mutation signature.
439 current_role: crate::vcs::Role,
440 /// The caller-declared identity for mutations and checks in this
441 /// session. Same session-state pattern as
442 /// `current_role`: set by the surface before each operation
443 /// (per-call parameter wins over the surface's session default);
444 /// `None` records as absence. An opaque caller-chosen string —
445 /// the engine neither generates, interprets, nor enriches it.
446 current_identity: Option<String>,
447 /// The transport's actor for commits the session causes without a
448 /// per-call actor (config writes, sync-state stamps, the anchor
449 /// writers): `Cli` under the CLI, `Agent` under the MCP server.
450 current_actor: crate::vcs::Actor,
451 /// The transport's client id, when it has one (the MCP client).
452 current_client: Option<crate::vcs::ClientId>,
453}
454
455/// Clock the engine reads when stamping mutation timestamps. `Arc`'d
456/// closure rather than a trait so a test can pin a constant with one
457/// line: `engine.set_mutation_clock(Arc::new(|| some_time))`.
458pub type MutationClock = Arc<dyn Fn() -> std::time::SystemTime + Send + Sync>;
459
460/// Backend factory function pointer. Both crates' existing
461/// `instantiate_*_backend` functions match this signature, so the
462/// type alias is what bridges the dependency direction (memstead-base
463/// can't depend on memstead-git-branch) without an extra trait.
464/// Stateless, `Send + Sync + Copy`.
465pub type BackendFactory =
466 fn(&Mount) -> Result<Box<dyn MemBackend>, crate::workspace_store::InstantiateError>;
467
468/// Per mem, what the merges recorded about the bodies adopted into it, as
469/// the origin read consults them.
470pub(crate) type ForeignMarks = HashMap<String, MemForeignMarks>;
471
472/// One mem's foreign-content marks: per slug, one prepared hash per
473/// load-bearing section of the body a merge adopted there, as no later
474/// disposition retired it.
475#[derive(Debug, Clone, Default, PartialEq, Eq)]
476pub(crate) struct MemForeignMarks {
477 /// Slug → (section key → prepared hash).
478 pub(crate) by_slug:
479 std::collections::BTreeMap<String, std::collections::BTreeMap<String, String>>,
480 /// Why the mem's proposal record could not be read, when it could not.
481 /// The marks are then unknown rather than absent, so every entity of the
482 /// mem reads third-party: a trust label may not fail open on a file it
483 /// could not read. The reason is kept so the label can say why
484 /// ([`Engine::proposal_record_error`]); a conservative label with no
485 /// stated cause is indistinguishable from the engine calling the
486 /// operator's own mem a stranger's.
487 pub(crate) record_unreadable: Option<String>,
488}
489
490impl MemForeignMarks {
491 pub(crate) fn unreadable(reason: String) -> Self {
492 Self {
493 by_slug: std::collections::BTreeMap::new(),
494 record_unreadable: Some(reason),
495 }
496 }
497}
498
499/// The validity key for derived-structure memos (flywheel W8/01):
500/// the store generation (bumped by every store mutation, carried by
501/// `Store::clone` so batch rollback restores it) plus the schemas
502/// epoch (bumped by every change to the engine's schema map). A memo
503/// is current exactly while both halves still match.
504///
505/// The foreign-mark memo additionally reads a mem's proposal record,
506/// which is in neither half; every act that changes a mark also mutates
507/// the store, so the key still covers it, and a writer outside the
508/// engine is the one case it would not.
509#[derive(Debug, Clone, Copy, PartialEq, Eq)]
510pub struct DerivedKey {
511 pub store_generation: u64,
512 pub schemas_epoch: u64,
513}
514
515/// Discovered storage for a mem that has NO mount record — the
516/// unmounted half of flywheel W7/02's write-time cross-mem target
517/// verification. The workspace layer owns the discovery convention
518/// (the mem-repo's branch registry, which memstead-base cannot see
519/// without inverting the crate dependency) and hands back a transient
520/// backend to ask plus the mem's schema pin when its config declares
521/// one, so the cross-schema edge routing can keep its authority
522/// without a mount.
523pub struct UnmountedMemStorage {
524 /// Transient backend over the discovered storage. Used for the
525 /// cheap [`MemBackend::entity_exists`] probe and the one-blob
526 /// type read — never registered, never loaded.
527 pub backend: Box<dyn MemBackend>,
528 /// The mem's pinned schema, when its stored config declares one.
529 pub schema: Option<memstead_schema::SchemaRef>,
530}
531
532/// Discovery hook: mem name → its storage, when the workspace layer
533/// can find any (`None` = no discoverable storage; the
534/// forward-reference mechanic governs, exactly as before). Boxed
535/// closure rather than a function pointer because discovery needs the
536/// workspace root and gitdir captured at boot.
537pub type UnmountedStorageProber = Box<dyn Fn(&str) -> Option<UnmountedMemStorage> + Send + Sync>;
538
539/// `Engine::changes_since` dispatch for git-branch mounts.
540///
541/// Signature matches `memstead_git_branch::ops::changes::changes_since` after
542/// adapting the `Store` parameter away (the engine performs enrichment
543/// downstream) and the `head_ref` parameter (`refs/heads/<branch>` is
544/// constructed inside the impl from `branch`).
545pub type GitBranchChangesSinceFn = fn(
546 gitdir: &Path,
547 branch: &str,
548 mem: &str,
549 since: &str,
550 rename_similarity: f32,
551) -> Result<crate::ops::BackendChanges, BackendError>;
552
553/// `Engine::export_mem` dispatch for git-branch mounts.
554///
555/// Signature mirrors `memstead_git_branch::ops::export::export_mem_from_branch`.
556pub type GitBranchExportFn = fn(
557 gitdir: &Path,
558 branch: &str,
559 mem: &str,
560 config: &memstead_schema::MemConfig,
561 output_path: &Path,
562 workspace_root: Option<&Path>,
563 workspace_schemas_dir: Option<&Path>,
564 // Engine-sourced authoring-provenance payload bytes (from the mount's
565 // `read_provenance` log) to embed at `.memstead/provenance.json`.
566 // `None` when the mem carried no noted mutations.
567 provenance_bytes: Option<&[u8]>,
568 // Engine-sourced anchors sidecar bytes (from the mount's
569 // `read_anchors_sidecar`) to embed at `.memstead/anchors.json`. `None`
570 // when the mem carried no anchors. The engine reads the branch tip; the
571 // hook only embeds, keeping git tree-walking out of the fn-pointer.
572 anchors_bytes: Option<&[u8]>,
573 // Engine-sourced sealed check records (from the workspace ledger) to
574 // embed at `.memstead/checks.json`. `None` when no record qualifies.
575 checks_bytes: Option<&[u8]>,
576) -> Result<crate::ops::MemExportResult, BackendError>;
577
578/// `Engine::export_mem_to_bytes` dispatch for git-branch mounts.
579///
580/// Signature mirrors `memstead_git_branch::ops::export::export_mem_from_branch_to_bytes`.
581/// Symmetric to `GitBranchExportFn`: same inputs minus the output path,
582/// returns archive bytes plus metadata instead of writing to disk.
583pub type GitBranchExportToBytesFn = fn(
584 gitdir: &Path,
585 branch: &str,
586 mem: &str,
587 config: &memstead_schema::MemConfig,
588 workspace_root: Option<&Path>,
589 workspace_schemas_dir: Option<&Path>,
590 // Pre-built authoring-provenance payload bytes the engine sourced from
591 // the mount's `read_provenance` log, to embed at
592 // `.memstead/provenance.json`. `None` when the mem carried no noted
593 // mutations. The engine sources it (it holds the backend); the hook
594 // only embeds, keeping git history-walking out of the fn-pointer.
595 provenance_bytes: Option<&[u8]>,
596 // Engine-sourced anchors sidecar bytes (from the mount's
597 // `read_anchors_sidecar`) to embed at `.memstead/anchors.json`. `None`
598 // when the mem carried no anchors. Symmetric with `provenance_bytes`:
599 // the engine reads the branch tip, the hook only embeds.
600 anchors_bytes: Option<&[u8]>,
601 // Engine-sourced sealed check records (from the workspace ledger) to
602 // embed at `.memstead/checks.json`. `None` when no record qualifies.
603 checks_bytes: Option<&[u8]>,
604) -> Result<crate::ops::MemExportBytes, BackendError>;
605
606/// `Engine::diff` dispatch for git-branch mounts. Walks the two refs
607/// inside the workspace's mem-repo gitdir, produces a per-entity
608/// [`crate::ops::Diff`]. Refs are arbitrary `gix::rev_parse_single`
609/// inputs — branch names, commit SHAs, tag names. Resolves each
610/// independently so cross-branch (cross-mem) diffs work uniformly.
611/// `branch` is the mount's declared branch; a bare `HEAD` token in
612/// either ref re-anchors onto it.
613pub type GitBranchDiffFn = fn(
614 gitdir: &Path,
615 branch: &str,
616 mem: &str,
617 ref_a: &str,
618 ref_b: &str,
619 config: &crate::ops::DiffConfig,
620) -> Result<crate::ops::Diff, BackendError>;
621
622/// `Engine::fetch` dispatch for git-branch mounts.
623pub type GitBranchFetchFn = fn(
624 gitdir: &Path,
625 remote: &str,
626 refspecs: &[String],
627) -> Result<crate::ops::FetchOutcome, BackendError>;
628
629/// Read every `.md` blob at `ref_name` in `gitdir`, returning
630/// `(relative_path, utf8_content)` pairs. Skips `.memstead/` engine-internal
631/// entries and non-blob nodes. Used by the pre-merge schema-validation
632/// pass `Engine::pull` and `Engine::push` run before they advance the
633/// branch pointer / push to the remote.
634pub type GitBranchReadTreeFn =
635 fn(gitdir: &Path, ref_name: &str) -> Result<Vec<(String, String)>, BackendError>;
636
637/// `Engine::pull` dispatch for git-branch mounts. `branch` is the
638/// mount's declared branch — the single source of truth for both the
639/// local ref and the remote-tracking ref; `mem` labels the outcome
640/// only.
641pub type GitBranchPullFn = fn(
642 gitdir: &Path,
643 remote: &str,
644 branch: &str,
645 mem: &str,
646) -> Result<crate::ops::PullOutcome, BackendError>;
647
648/// `Engine::push` dispatch for git-branch mounts. `branch` is the
649/// mount's declared branch (see [`GitBranchPullFn`]); `mem` labels
650/// the outcome only.
651pub type GitBranchPushFn = fn(
652 gitdir: &Path,
653 remote: &str,
654 branch: &str,
655 mem: &str,
656 force: bool,
657) -> Result<crate::ops::PushOutcome, BackendError>;
658
659/// `Engine::push_all` dispatch, first half: the remote's ref table
660/// in one round-trip (`git ls-remote --heads`), as `(full ref name,
661/// sha)` pairs. Lets the engine tell a lagging ref from one already
662/// in sync before it sends anything.
663pub type GitBranchLsRemoteFn =
664 fn(gitdir: &Path, remote: &str) -> Result<Vec<(String, String)>, BackendError>;
665
666/// `Engine::push_all` dispatch, second half: resolve one local ref
667/// to its SHA. `Ok(None)` when the ref does not exist (a fresh
668/// mem-repo legitimately has no `__MEMSTEAD` yet).
669pub type GitBranchResolveRefFn =
670 fn(gitdir: &Path, ref_name: &str) -> Result<Option<String>, BackendError>;
671
672/// `Engine::remote_status` dispatch: whether `ancestor` is reachable
673/// from `descendant` in the gitdir's history (`git merge-base
674/// --is-ancestor`). Read-only; tells local-ahead from behind from forked
675/// without moving a ref.
676pub type GitBranchIsAncestorFn =
677 fn(gitdir: &Path, ancestor: &str, descendant: &str) -> Result<bool, BackendError>;
678
679/// The nearest common ancestor of two commits (`git merge-base`);
680/// `None` when they share no history. Read-only. The adopt form of
681/// `mem fork` reads the ancestor of a fork branch that arrived on a
682/// remote off it.
683pub type GitBranchMergeBaseFn =
684 fn(gitdir: &Path, a: &str, b: &str) -> Result<Option<String>, BackendError>;
685
686/// Point `ref_name` at `sha`, creating the ref when absent and
687/// moving it unconditionally when present. Engine-internal, for refs
688/// the engine derives and owns outright (the check-ledger transport
689/// ref, whose content is re-derived from the workspace ledger before
690/// every publish); never a mem's branch.
691pub type GitBranchUpdateRefFn =
692 fn(gitdir: &Path, ref_name: &str, sha: &str) -> Result<(), BackendError>;
693
694/// `Engine::remote_add` dispatch — configures a named remote on the
695/// mem-repo gitdir (upsert: add, or set-url when it already exists).
696pub type GitBranchRemoteAddFn =
697 fn(gitdir: &Path, name: &str, url: &str) -> Result<crate::ops::RemoteAddOutcome, BackendError>;
698
699/// `Engine::branch_reset` dispatch for git-branch mounts. Returns the
700/// outcome on success; surfaces `BackendError::Other` carrying an
701/// in-band marker (`UNKNOWN_REF:<raw>` or
702/// `PUSHED_COMMITS_PROTECTED:<sha,sha,...>`) the engine layer
703/// un-marshals into typed `EngineError`s.
704pub type GitBranchBranchResetFn = fn(
705 gitdir: &Path,
706 branch: &str,
707 target_sha: &str,
708 expected_head: Option<&str>,
709) -> Result<crate::ops::BranchResetOutcome, BackendError>;
710
711/// Residue-prune dispatch for git-branch mounts.
712/// The `create_mem` orchestrator calls this when
713/// `RecoveryAction::ForceOverwrite` is selected against pre-existing
714/// storage residue. Drops `refs/heads/<branch_full_path>` and the
715/// `__MEMSTEAD:mems/<branch_full_path>/config.json` blob in one
716/// ref-edit transaction (the same call the
717/// `MemBackend::delete_artifacts` impl wraps for delete-files
718/// flows). Surfaces as a function pointer so `crate::mem_management`
719/// can drive a prune against an unmounted gitdir without depending on
720/// `memstead-git-branch`.
721pub type GitBranchPruneResidueFn = fn(
722 gitdir: &Path,
723 branch_full_path: &str,
724 ctx: &crate::vcs::CommitContext<'_>,
725) -> Result<(), BackendError>;
726
727/// Config-only prune: drop the mem's blobs on `__MEMSTEAD` and leave
728/// every content branch alone. `create_mem` rolls a failed seed commit
729/// back through it so no config outlives the mem it was written for;
730/// `delete_mem` removes a config left behind that way. Idempotent.
731pub type GitBranchPruneConfigBlobFn = fn(
732 gitdir: &Path,
733 branch_full_path: &str,
734 ctx: &crate::vcs::CommitContext<'_>,
735) -> Result<(), BackendError>;
736
737/// Ref-namespace probe: the local branches a new
738/// `refs/heads/<branch_full_path>` could not coexist with, because
739/// one is a path prefix of the other (git keeps refs as files in
740/// directories). `create_mem` asks before it writes anything.
741pub type GitBranchNamespaceConflictsFn =
742 fn(gitdir: &Path, branch_full_path: &str) -> Result<Vec<String>, BackendError>;
743
744/// `fork_mem` dispatch: create `refs/heads/<branch_full_path>` at
745/// `sha`, a full commit id already in the object store, in one
746/// ref-edit that refuses when the ref exists. The branch is the
747/// fork's lineage claim: its first commit is the source's, never a
748/// fresh seed.
749pub type GitBranchCreateBranchAtFn =
750 fn(gitdir: &Path, branch_full_path: &str, sha: &str) -> Result<(), BackendError>;
751
752/// `fork_mem` dispatch for the remote form: one mem's config blob
753/// (`mems/<mem>/config.json`) from the `__MEMSTEAD` tree at
754/// `ref_name`, the remote-tracking ref a fetch just placed
755/// (`refs/remotes/<remote>/__MEMSTEAD`), never the local
756/// `refs/heads/__MEMSTEAD`. `Ok(None)` when the ref or the blob is
757/// absent. Read-only.
758pub type GitBranchReadConfigAtRefFn =
759 fn(gitdir: &Path, ref_name: &str, mem: &str) -> Result<Option<Vec<u8>>, BackendError>;
760
761/// `rename_mem` dispatch for the git-branch backend: move the mem's
762/// content branch `refs/heads/<old>` to `refs/heads/<new>` at the same
763/// tip (history preserved) and relocate the `__MEMSTEAD:mems/<old>/`
764/// config blob to `mems/<new>/`, all in one ref-edit transaction.
765/// Refuses (no mutation) when the source branch is missing or the
766/// target branch already exists.
767pub type GitBranchRenameMemStorageFn = fn(
768 gitdir: &Path,
769 old_leaf: &str,
770 new_leaf: &str,
771 ctx: &crate::vcs::CommitContext<'_>,
772) -> Result<(), BackendError>;
773
774/// `Engine::install_schema` dispatch for the git-branch backend: write a
775/// schema package (`(relative-path, bytes)` pairs) onto the workspace's
776/// unified `__MEMSTEAD:schemas/<name>@<version>/` ref and return the
777/// resulting commit sha. Mirrors
778/// `memstead_git_branch::storage_memstead::write_schema_to_memstead_ref`.
779pub type GitBranchWriteSchemaFn = fn(
780 gitdir: &Path,
781 name: &str,
782 version: &str,
783 files: &[(String, Vec<u8>)],
784) -> Result<String, BackendError>;
785
786/// Read one file from a sealed schema package on the workspace's
787/// `__MEMSTEAD:schemas/<name>@<version>/` ref. `Ok(None)` when the
788/// ref, package, or file is absent — absence is a normal state (the
789/// install-provenance stamp only exists for path-sourced installs).
790/// Read-only; the authoring-drift health axis is the consumer.
791pub type GitBranchReadSchemaFileFn = fn(
792 gitdir: &Path,
793 name: &str,
794 version: &str,
795 rel: &str,
796) -> Result<Option<Vec<u8>>, BackendError>;
797
798/// Re-read every schema sealed on the workspace's
799/// `__MEMSTEAD:schemas/` ref (empty when the ref or subtree is
800/// absent). Read-only; `Engine::full_refresh` is the consumer — the
801/// warm-server path that makes an out-of-band `memstead schema
802/// install` resolvable without a process restart.
803pub type GitBranchReadRefSchemasFn =
804 fn(workspace_root: &Path) -> Result<Vec<Arc<memstead_schema::Schema>>, BackendError>;
805
806/// Collect one pinned schema's raw source files (manifest, sealed
807/// format marker, type definitions) from the workspace's
808/// `__MEMSTEAD:schemas/<name>@<version>/` ref — the tree `memstead
809/// schema install` writes on the git-branch backend. `Ok(None)` when
810/// the workspace has no mem-repo, the ref, or the package. Read-only;
811/// the consumer is the FOLDER-mount export path: a folder mem living
812/// in a mem-repo workspace pins a schema the installer sealed on the
813/// ref, so the archive assembler must read the same store the loader
814/// resolves from, or the mem loads but cannot export.
815pub type GitBranchCollectSchemaSourceFn =
816 fn(
817 workspace_root: &Path,
818 schema_ref: &memstead_schema::SchemaRef,
819 ) -> Result<Option<Vec<memstead_schema::SchemaSourceFile>>, BackendError>;
820
821/// Bundle of git-branch-specific op dispatchers. Installed on the
822/// engine at full boot. Each field is one ops-method that previously
823/// lived on the `MemBackend` trait; moving them off the trait keeps
824/// the bytes-level primitive surface clean.
825#[derive(Clone, Copy)]
826pub struct GitBranchOps {
827 pub changes_since: GitBranchChangesSinceFn,
828 pub diff: GitBranchDiffFn,
829 pub branch_reset: GitBranchBranchResetFn,
830 pub fetch: GitBranchFetchFn,
831 pub pull: GitBranchPullFn,
832 pub push: GitBranchPushFn,
833 pub ls_remote: GitBranchLsRemoteFn,
834 pub resolve_ref: GitBranchResolveRefFn,
835 pub is_ancestor: GitBranchIsAncestorFn,
836 pub merge_base: GitBranchMergeBaseFn,
837 pub update_ref: GitBranchUpdateRefFn,
838 pub remote_add: GitBranchRemoteAddFn,
839 pub read_tree: GitBranchReadTreeFn,
840 pub export: GitBranchExportFn,
841 pub export_to_bytes: GitBranchExportToBytesFn,
842 pub prune_residue: GitBranchPruneResidueFn,
843 pub prune_config_blob: GitBranchPruneConfigBlobFn,
844 pub branch_namespace_conflicts: GitBranchNamespaceConflictsFn,
845 pub create_branch_at: GitBranchCreateBranchAtFn,
846 pub read_config_at_ref: GitBranchReadConfigAtRefFn,
847 pub rename_mem_storage: GitBranchRenameMemStorageFn,
848 pub write_schema: GitBranchWriteSchemaFn,
849 pub read_schema_file: GitBranchReadSchemaFileFn,
850 pub read_ref_schemas: GitBranchReadRefSchemasFn,
851 pub collect_ref_schema_source: GitBranchCollectSchemaSourceFn,
852}
853
854impl std::fmt::Debug for Engine {
855 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
856 f.debug_struct("Engine")
857 .field(
858 "mems",
859 &self
860 .mounts
861 .iter()
862 .map(|m| m.mount.mem.as_str())
863 .collect::<Vec<_>>(),
864 )
865 .finish()
866 }
867}
868
869#[cfg(test)]
870mod in_memory_mem;
871
872#[cfg(test)]
873pub(super) mod test_helpers {
874 use std::io::Write as _;
875 use std::path::{Path, PathBuf};
876
877 use memstead_schema::SchemaRef;
878
879 use crate::backend::MemBackend;
880 use crate::storage::FilesystemBackend;
881 use crate::vcs::{Actor, ClientId};
882 use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
883
884 use super::{CreateEntityArgs, CreateEntityOutcome, Engine, RelateEntityArgs};
885
886 use indexmap::IndexMap;
887 use tempfile::TempDir;
888
889 pub(crate) fn pin(name: &str) -> SchemaRef {
890 let version = match name {
891 "default" => semver::Version::new(1, 0, 0),
892 _ => semver::Version::new(0, 1, 0),
893 };
894 SchemaRef::new(name, version)
895 }
896
897 pub(crate) fn folder_mount(mem: &str, path: PathBuf) -> Mount {
898 Mount {
899 mem: mem.to_string(),
900 schema: Some(pin("default")),
901 storage: MountStorage::Folder { path },
902 capability: MountCapability::Write,
903 lifecycle: MountLifecycle::Eager,
904 cross_linkable: true,
905 migration_target: None,
906 }
907 }
908
909 pub(crate) fn in_memory_mount(mem: &str) -> Mount {
910 Mount {
911 mem: mem.to_string(),
912 schema: Some(pin("default")),
913 storage: MountStorage::InMemory,
914 capability: MountCapability::Write,
915 lifecycle: MountLifecycle::Eager,
916 cross_linkable: true,
917 migration_target: None,
918 }
919 }
920
921 pub(crate) fn archive_mount(mem: &str, path: PathBuf) -> Mount {
922 Mount {
923 mem: mem.to_string(),
924 schema: Some(pin("default")),
925 storage: MountStorage::Archive { path },
926 capability: MountCapability::ReadOnly,
927 // Eager, matching every production archive-mount site: these
928 // tests pin archive READ semantics over a loaded store. The
929 // lifecycle slot became real (flywheel W7/01) — a `Lazy`
930 // value here would defer the load these tests read through.
931 // The lazy behaviour has its own tests in `boot.rs`.
932 lifecycle: MountLifecycle::Eager,
933 cross_linkable: false,
934 migration_target: None,
935 }
936 }
937
938 /// Build a sealed archive at `tmp/<name>.mem` from
939 /// `(relative_path, bytes)` pairs and return the path.
940 pub(crate) fn build_archive(tmp: &Path, name: &str, entries: &[(&str, &[u8])]) -> PathBuf {
941 let path = tmp.join(format!("{name}.mem"));
942 let file = std::fs::File::create(&path).unwrap();
943 let mut writer = zip::ZipWriter::new(file);
944 let opts = zip::write::SimpleFileOptions::default();
945 for (rel, bytes) in entries {
946 writer.start_file(*rel, opts).unwrap();
947 writer.write_all(bytes).unwrap();
948 }
949 writer.finish().unwrap();
950 path
951 }
952
953 /// Write a schema manifest + minimal type bodies under
954 /// `<root>/<name>/`. Each type gets a body with a single
955 /// `body` section and `_default` hierarchy/no-self-loop lists — enough
956 /// to load and parse markdown that uses that type. Used by tests
957 /// that need a custom schema with shape or vocabulary constraints.
958 pub(crate) fn write_schema_files_with_default_type(
959 root: &Path,
960 name: &str,
961 manifest: &str,
962 types: &[&str],
963 ) {
964 const TYPE_BODY: &str = r#"description: t
965when_to_use: Here
966sections:
967 - key: body
968 heading: Body
969 required: true
970 search_weight: 10.0
971 catch_all: true
972 write_rules: []
973metadata_fields: []
974title_weight: 100.0
975text_fields:
976 - body
977hierarchy_relationship: _default
978no_self_loop_relationships: []
979updatable_fields:
980 - title
981 - body
982health_required_fields:
983 - body
984staleness_threshold_days: 90
985write_rules: []
986"#;
987 let dir = root.join(name);
988 std::fs::create_dir_all(dir.join("types")).unwrap();
989 std::fs::write(dir.join("schema.yaml"), manifest).unwrap();
990 for type_name in types {
991 let body = format!("name: {type_name}\n{TYPE_BODY}");
992 std::fs::write(dir.join("types").join(format!("{type_name}.yaml")), body).unwrap();
993 }
994 }
995
996 pub(crate) fn empty_create_args(mem: &str, title: &str) -> CreateEntityArgs {
997 // The
998 // create path refuses on missing required sections. The
999 // default `spec` type requires `identity` + `purpose`. Seed
1000 // both with a single space so the test fixture remains a
1001 // valid creation request — every test that uses this helper
1002 // as a fixture builder continues to work, and tests that
1003 // specifically exercise the refusal supply an explicit
1004 // empty-sections payload (see the dedicated refusal tests).
1005 let mut sections = IndexMap::new();
1006 sections.insert("identity".to_string(), "fixture identity body".to_string());
1007 sections.insert("purpose".to_string(), "fixture purpose body".to_string());
1008 CreateEntityArgs {
1009 anchors: Vec::new(),
1010 mem: mem.to_string(),
1011 title: title.to_string(),
1012 entity_type: "spec".to_string(),
1013 sections,
1014 metadata: IndexMap::new(),
1015 relations: Vec::new(),
1016 dry_run: false,
1017 }
1018 }
1019
1020 pub(crate) fn cli_actor() -> (Actor, ClientId) {
1021 (
1022 Actor::Cli,
1023 ClientId {
1024 name: "claude-code".to_string(),
1025 version: "2.1.0".to_string(),
1026 },
1027 )
1028 }
1029
1030 pub(crate) fn engine_with_seed(tmp: &TempDir, title: &str) -> (Engine, CreateEntityOutcome) {
1031 let mem_dir = tmp.path().to_path_buf();
1032 let writer = FilesystemBackend::new(mem_dir.clone());
1033 let mut engine = Engine::from_mounts(vec![(
1034 folder_mount("specs", mem_dir),
1035 Box::new(writer) as Box<dyn MemBackend>,
1036 )])
1037 .unwrap();
1038 let (actor, client) = cli_actor();
1039 let outcome = engine
1040 .create_entity(
1041 empty_create_args("specs", title),
1042 actor,
1043 Some(&client),
1044 None,
1045 )
1046 .unwrap();
1047 (engine, outcome)
1048 }
1049 pub(crate) fn build_demo_engine(tmp: &TempDir) -> Engine {
1050 let mem_dir = tmp.path().to_path_buf();
1051 let writer = FilesystemBackend::new(mem_dir.clone());
1052 let mut engine = Engine::from_mounts(vec![(
1053 folder_mount("specs", mem_dir),
1054 Box::new(writer) as Box<dyn MemBackend>,
1055 )])
1056 .unwrap();
1057 let (actor, client) = cli_actor();
1058 let source = engine
1059 .create_entity(
1060 empty_create_args("specs", "Source One"),
1061 actor,
1062 Some(&client),
1063 None,
1064 )
1065 .unwrap();
1066 let target = engine
1067 .create_entity(
1068 empty_create_args("specs", "Target Two"),
1069 actor,
1070 Some(&client),
1071 None,
1072 )
1073 .unwrap();
1074 engine
1075 .create_entity(
1076 empty_create_args("specs", "Lonely Three"),
1077 actor,
1078 Some(&client),
1079 None,
1080 )
1081 .unwrap();
1082 engine
1083 .relate_entity(
1084 RelateEntityArgs {
1085 source: source.id.clone(),
1086 expected_hash: Some(source.content_hash.clone()),
1087 rel_type: "USES".to_string(),
1088 target: target.id.clone(),
1089 remove: false,
1090 description: None,
1091 dry_run: false,
1092 },
1093 actor,
1094 Some(&client),
1095 None,
1096 )
1097 .unwrap();
1098 engine
1099 }
1100}