Skip to main content

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