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. The MCP filesystem-mem server
6//! (`memstead_mcp::filesystem_server::FilesystemMcpServer`), every CLI
7//! lean subcommand, and the macOS UniFFI consumer all reach the
8//! engine through [`Engine::from_workspace_root`] (lean: folder +
9//! archive backends) or `memstead_git_branch::engine_from_workspace_root`
10//! (full: adds git-branch).
11//!
12//! ## Routing
13//!
14//! Each mount holds one mem. Lookup is by mem name: the first
15//! mount whose `mem` field equals the requested name wins. One mount
16//! per mem is enforced — duplicates are a configuration bug, not a
17//! feature, and the constructor rejects them.
18
19use std::cell::OnceCell;
20use std::collections::HashMap;
21use std::path::{Path, PathBuf};
22use std::sync::Arc;
23
24use memstead_schema::Schema;
25
26use crate::backend::{BackendError, MemBackend};
27use crate::graph::LouvainOutput;
28use crate::mem::MemRouterSnapshot;
29use crate::ops::WarningHint;
30#[cfg(not(target_arch = "wasm32"))]
31use crate::search_index::MemIndex;
32use crate::store::Store;
33use crate::workspace::{Mount, WorkspaceSettings};
34
35pub mod apply_commit;
36pub mod archive;
37pub mod boot;
38pub mod drift;
39pub mod error;
40pub mod events;
41#[cfg(feature = "file-watcher")]
42pub mod file_watcher;
43pub mod lifecycle;
44pub mod mutation;
45pub mod outcomes;
46pub mod query;
47
48pub use archive::FromArchiveBytesError;
49pub use error::{
50    BootError, EngineError, INLINE_LIST_CAP, MissingWikiLink, ReferrerInfo, SchemaSourceDiagnostic,
51    format_inline_list_overflow,
52};
53#[cfg(feature = "tokio")]
54pub use events::DEFAULT_BROADCAST_CAPACITY;
55pub use events::{EventCallback, MemChangedEvent, SubscriptionHandle};
56#[cfg(feature = "file-watcher")]
57pub use file_watcher::{FileWatcherError, MemRepoWatcher, watch_mem_repo};
58pub use mutation::delete::DeleteReferrers;
59pub use mutation::{PATCH_OLD_NOT_FOUND_CONTENT_CAP, RELATIONSHIP_CYCLE_PATH_CAP};
60pub use outcomes::{
61    CreateEntityArgs, CreateEntityOutcome, DeleteEntityArgs, DeleteEntityOutcome, RelateAction,
62    RelateEntityArgs, RelateEntityOutcome, RenameEntityArgs, RenameEntityOutcome, SetSchemaOutcome,
63    SetSchemaResult, UpdateEntityArgs, UpdateEntityOutcome,
64};
65
66pub use boot::{SchemaResolver, resolve_builtin_schema_pin_pub};
67
68/// One mem attachment, paired with the backend that serves it.
69/// Constructed by [`Engine::from_mounts`] and held internally.
70struct MountedBackend {
71    mount: Mount,
72    backend: Box<dyn MemBackend>,
73    /// Last cursor returned by `backend.current_head()`. Seeded in
74    /// [`Engine::from_mounts`]; refreshed by
75    /// [`Engine::reload_if_stale`] after a successful reload.
76    /// `None` means the backend doesn't track a head (folder /
77    /// archive) — drift detection is a no-op for this mount.
78    last_known_head: Option<String>,
79    /// Per-mem `.memstead/config.json` payload — surfaces via
80    /// [`Engine::mem_config_for`] for handlers that need
81    /// `write_guidance` / `extra` (`memstead_health
82    /// { include_config: true }`'s per-mem detail block).
83    ///
84    /// Loaded at construction for folder backends (read from
85    /// `<path>/.memstead/config.json`). Git-branch + archive backends
86    /// carry `None` for now — the read-from-storage-backend path
87    /// lifts in a follow-up session.
88    mem_config: Option<memstead_schema::config::MemConfig>,
89    /// Per-mem authoring-provenance payload read from the archive's
90    /// `.memstead/provenance.json` at construction (via
91    /// [`crate::backend::MemBackend::read_archive_provenance`]). `None`
92    /// when the backend carries no provenance member (a pre-provenance
93    /// archive, or a backend that does not surface one) — surfaced as
94    /// provenance-absent via [`Engine::archive_provenance_for`]. A
95    /// malformed payload is downgraded to `None` rather than failing the
96    /// mount: the member is additive.
97    archive_provenance: Option<memstead_schema::ArchiveProvenance>,
98}
99
100/// Unified engine. Holds a list of mounted backends and routes
101/// mem-named operations to the right one.
102///
103/// `Send` so the engine can sit behind a `Mutex` (today's pattern
104/// in the MCP server). The trait object's `Send + Sync` bound on
105/// `MemBackend` keeps the inner backends thread-safe; the engine
106/// itself is single-threaded by design (the lazy memos are
107/// `OnceCell`, which is `!Sync`).
108///
109/// `Debug` is hand-written to avoid requiring `Debug` on the
110/// `dyn MemBackend` trait object — backend impls are free to
111/// stay non-`Debug`.
112///
113/// ## Load-on-init
114///
115/// `Engine::from_mounts` walks each backend at construction time
116/// (`list_entities` + `read_entity` + parse) and populates a single
117/// shared [`Store`] with entities and edges from every mount. Each
118/// mount's schema resolves from its own pin (the backend config's
119/// schema, or the mount-record assertion as fallback) through the
120/// `SchemaResolver`, so `schemas` holds genuinely heterogeneous
121/// schemas in a multi-schema workspace. Per-file errors don't fail
122/// construction; they collect into [`Engine::load_errors`] for the
123/// operator to inspect.
124pub struct Engine {
125    mounts: Vec<MountedBackend>,
126    store: Store,
127    schemas: HashMap<String, Arc<Schema>>,
128    /// Workspace-authored schemas loaded from
129    /// `WorkspaceSettings.schemas_dir` at construction. Distinct from
130    /// `schemas` (per-mem, only schemas pinned by a mount): this
131    /// catalogue carries every workspace-loaded schema regardless of
132    /// whether a mem pins it. Surfaced via
133    /// [`Self::workspace_schemas`] for handlers that need to enumerate
134    /// schemas referenced by `mem_create_rules.schemas[]` but not
135    /// pinned by any mem — `memstead_overview` lists them in `## Schemas`
136    /// so an agent sees what could be pinned. Empty when no
137    /// `schemas_dir` was passed.
138    workspace_schemas: Vec<Arc<Schema>>,
139    /// Embedded built-in schemas loaded once at boot from
140    /// `memstead_schema::builtins::load_builtin_schemas()`. The boot path
141    /// uses this catalogue to resolve each mount's schema pin; storing
142    /// it on the engine lets read handlers (MCP's `memstead_schema`,
143    /// `memstead_overview`'s `## Schemas` rendering) surface every built-in
144    /// without re-walking the embedded directory. Schemas declared in
145    /// `workspace_schemas` shadow built-ins on `(name, version)`
146    /// collision — handlers walking both lists must check workspace
147    /// first.
148    builtin_schemas: Vec<Arc<Schema>>,
149    load_errors: Vec<(PathBuf, String)>,
150    /// Lazily-computed Louvain community detection across the
151    /// engine-wide store. Populated on first call to
152    /// [`Self::communities`]; invalidated by
153    /// [`Self::invalidate_communities`] which every mutation method
154    /// calls after a successful write. `OnceCell` is `!Sync`; the
155    /// engine is `Send` (it is moved into a `Mutex` by every consumer)
156    /// but not `Sync`.
157    community_memo: OnceCell<LouvainOutput>,
158    /// Lazily-computed per-mem search index map. Built on first call
159    /// to [`Self::search_indexes`] via [`build_all`]; invalidated by
160    /// [`Self::invalidate_search_indexes`] alongside the community
161    /// cache so every mutation triggers a fresh build on the next
162    /// search. Absent on `wasm32` targets — search lives behind the
163    /// bridge (see `EngineError::SearchUnavailable`).
164    #[cfg(not(target_arch = "wasm32"))]
165    search_indexes_memo: OnceCell<HashMap<String, MemIndex>>,
166    /// Workspace-level operator policy — mem create/delete rules,
167    /// cross-mem link permissions. Defaults to empty; populated via
168    /// [`Self::set_settings`] when [`Self::from_workspace_root`] (or
169    /// the full counterpart) reads `.memstead/workspace.toml`. Surfaced
170    /// read-only via [`Self::settings`] for MCP handlers and other
171    /// consumers.
172    settings: WorkspaceSettings,
173    /// Lazily-compiled [`crate::mem_management::CreateRuleSet`] over
174    /// `settings.mem_create_rules`. Built on first
175    /// [`Self::cross_mem_link_allowed`] call that needs synthesis;
176    /// invalidated by [`Self::set_settings`] (so a fresh policy
177    /// re-compiles on the next call). Compilation errors are logged
178    /// and the cache stays empty — synthesis is best-effort, the
179    /// resolver falls back to explicit-policy resolution. Operators
180    /// who want hard validation pre-compile via
181    /// [`crate::mem_management::CreateRuleSet::new`] before passing
182    /// settings.
183    create_rule_set_memo: OnceCell<crate::mem_management::CreateRuleSet>,
184    /// Workspace root path — set when the engine boots from a
185    /// workspace store ([`Self::from_workspace_root`] or the full
186    /// counterpart). `None` for tests + ad-hoc consumers that build
187    /// the engine directly from a mount list. Surfaced via
188    /// [`Self::workspace_root`] for handlers that need filesystem
189    /// context (e.g. [`Self::health`]'s outer-repo .gitignore
190    /// check).
191    workspace_root: Option<PathBuf>,
192    /// Typed warnings surfaced during mem load — drift findings
193    /// like [`WarningHint::SuspiciousNestedPrefix`] and
194    /// [`WarningHint::DuplicateSectionHeading`] that the loader
195    /// pipeline collects per entity. Empty for the V1 unified
196    /// engine; the field is in place so handlers and the health
197    /// surface can include them when the loader pipeline grows the
198    /// warning generators.
199    load_warnings: Vec<WarningHint>,
200    /// Pipeline configs (Medium / Facet / Projection / Ingest) loaded
201    /// from the workspace store at boot. Empty for engines built via
202    /// `from_mounts*` (tests, in-memory consumers) and for any workspace
203    /// that declares no pipelines; the workspace-root boot paths
204    /// (`from_workspace_root` and the full counterpart) populate it via
205    /// [`crate::pipeline_store::load_pipeline_configs`]. Read-only
206    /// runtime surface — exposed through [`Self::pipeline_configs`]; the
207    /// engine neither runs nor schedules pipelines (the ingest skill and
208    /// future consumers do).
209    pipeline_configs: crate::pipeline_store::PipelineConfigs,
210    /// Runtime snapshot of writable / visible mems. Derived from
211    /// the mount list at construction: writable mounts
212    /// (`MountCapability::Write`) register via `add_writable` with
213    /// the storage's directory path (folder → `path`, git-branch →
214    /// None, archive shouldn't be writable); read-only mounts
215    /// register via `add_writable` (folder/git-branch) or
216    /// `add_read_only` (archive). Used by MCP handlers that need the
217    /// writable/visible roster + per-mem origin (`memstead_health
218    /// include_config: true`, `memstead_overview`'s mem list,
219    /// `memstead_mem_create`'s collision check).
220    ///
221    /// Wrapped in `Arc` so the COW-snapshot discipline — clone the
222    /// snapshot, mutate the clone, swap the `Arc` — keeps writers
223    /// and concurrent readers from contending on the live mount
224    /// list.
225    mem_router: Arc<MemRouterSnapshot>,
226    /// Backend factory — function pointer used by
227    /// [`crate::mem_management::create_mem`] (and future runtime
228    /// mount-add paths) to materialise a [`MemBackend`] from a
229    /// [`Mount`] declaration. Defaults to
230    /// [`crate::workspace_store::instantiate_lean_backend`] so lean
231    /// (folder + archive only) consumers work out of the box. Full
232    /// consumers swap in `memstead_git_branch::storage::instantiate_full_backend`
233    /// via [`Self::set_backend_factory`] after constructing the engine —
234    /// `engine_from_workspace_root` does this once at boot. Function
235    /// pointer (not `Box<dyn Fn>`) because the backend factory is
236    /// stateless, `Send + Sync + Copy`, and one less allocation on the
237    /// hot path matters for the multi-mem pattern this engine is
238    /// designed around.
239    backend_factory: BackendFactory,
240    /// Git-branch ops bundle — function pointers for the per-mount
241    /// operations whose implementations live in `memstead-git-branch`
242    /// (and therefore can't sit on the `MemBackend` trait without
243    /// inverting the crate dependency). Full boot
244    /// (`memstead_git_branch::engine_from_workspace_root`) installs the
245    /// bundle via [`Self::set_git_branch_ops`]; lean consumers leave
246    /// it `None` and `Engine::changes_since` / `Engine::export_mem`
247    /// fall through to the folder/archive-only branches.
248    git_branch_ops: Option<GitBranchOps>,
249    /// Per-mem subscriber registry for [`MemChangedEvent`]s. Held
250    /// behind `Arc<Mutex<_>>` so [`SubscriptionHandle`]s — which own
251    /// the consumer's view of the subscription lifetime — can call
252    /// back into the registry on `Drop` without a self-reference cycle
253    /// to the engine. The emit path (in `record_self_write`) snapshots
254    /// the per-mem callback list under the lock, releases the lock,
255    /// and then invokes the callbacks — so a callback that re-enters
256    /// the engine for a read does not deadlock against the registry.
257    event_subscribers: Arc<std::sync::Mutex<events::SubscriberRegistry>>,
258    /// Reload-before-operation notices accumulated by
259    /// [`Self::reload_if_stale`] when an operation triggered a mem
260    /// reload. Built at reload time — when the backend's current head
261    /// equals the head we reloaded to, *before* any mutation in the
262    /// same operation commits — so the delta describes only the
263    /// sibling's change, never the engine's own follow-on write. The
264    /// response layer drains them via
265    /// [`Self::take_mem_changed_notices`] and attaches the structured
266    /// `mem_changed` notice to the operation's response. Every entity
267    /// op that can reload drains after; an undrained accumulation would
268    /// leak into the next operation's response, so callers that reload
269    /// must take.
270    pending_mem_changed: Vec<crate::ops::MemChangedNotice>,
271}
272
273/// Backend factory function pointer. Both flavours' existing
274/// `instantiate_*_backend` functions match this signature, so the
275/// type alias is what bridges the dependency direction (memstead-base
276/// can't depend on memstead-git-branch) without an extra trait.
277/// Stateless, `Send + Sync + Copy`.
278pub type BackendFactory =
279    fn(&Mount) -> Result<Box<dyn MemBackend>, crate::workspace_store::InstantiateError>;
280
281/// `Engine::changes_since` dispatch for git-branch mounts.
282///
283/// Signature matches `memstead_git_branch::ops::changes::changes_since` after
284/// adapting the `Store` parameter away (the engine performs enrichment
285/// downstream) and the `head_ref` parameter (`refs/heads/<branch>` is
286/// constructed inside the impl from `branch`).
287pub type GitBranchChangesSinceFn = fn(
288    gitdir: &Path,
289    branch: &str,
290    mem: &str,
291    since: &str,
292    rename_similarity: f32,
293) -> Result<crate::ops::BackendChanges, BackendError>;
294
295/// `Engine::export_mem` dispatch for git-branch mounts.
296///
297/// Signature mirrors `memstead_git_branch::ops::export::export_mem_from_branch`.
298pub type GitBranchExportFn = fn(
299    gitdir: &Path,
300    branch: &str,
301    mem: &str,
302    config: &memstead_schema::MemConfig,
303    output_path: &Path,
304    workspace_root: Option<&Path>,
305    workspace_schemas_dir: Option<&Path>,
306    // Engine-sourced authoring-provenance payload bytes (from the mount's
307    // `read_provenance` log) to embed at `.memstead/provenance.json`.
308    // `None` when the mem carried no noted mutations.
309    provenance_bytes: Option<&[u8]>,
310) -> Result<crate::ops::MemExportResult, BackendError>;
311
312/// `Engine::export_mem_to_bytes` dispatch for git-branch mounts.
313///
314/// Signature mirrors `memstead_git_branch::ops::export::export_mem_from_branch_to_bytes`.
315/// Symmetric to `GitBranchExportFn`: same inputs minus the output path,
316/// returns archive bytes plus metadata instead of writing to disk.
317pub type GitBranchExportToBytesFn = fn(
318    gitdir: &Path,
319    branch: &str,
320    mem: &str,
321    config: &memstead_schema::MemConfig,
322    workspace_root: Option<&Path>,
323    workspace_schemas_dir: Option<&Path>,
324    // Pre-built authoring-provenance payload bytes the engine sourced from
325    // the mount's `read_provenance` log, to embed at
326    // `.memstead/provenance.json`. `None` when the mem carried no noted
327    // mutations. The engine sources it (it holds the backend); the hook
328    // only embeds, keeping git history-walking out of the fn-pointer.
329    provenance_bytes: Option<&[u8]>,
330) -> Result<crate::ops::MemExportBytes, BackendError>;
331
332/// `Engine::diff` dispatch for git-branch mounts. Walks the two refs
333/// inside the workspace's mem-repo gitdir, produces a per-entity
334/// [`crate::ops::Diff`]. Refs are arbitrary `gix::rev_parse_single`
335/// inputs — branch names, commit SHAs, tag names. Resolves each
336/// independently so cross-branch (cross-mem) diffs work uniformly.
337pub type GitBranchDiffFn = fn(
338    gitdir: &Path,
339    mem: &str,
340    ref_a: &str,
341    ref_b: &str,
342    config: &crate::ops::DiffConfig,
343) -> Result<crate::ops::Diff, BackendError>;
344
345/// `Engine::fetch` dispatch for git-branch mounts.
346pub type GitBranchFetchFn = fn(
347    gitdir: &Path,
348    remote: &str,
349    refspecs: &[String],
350) -> Result<crate::ops::FetchOutcome, BackendError>;
351
352/// Read every `.md` blob at `ref_name` in `gitdir`, returning
353/// `(relative_path, utf8_content)` pairs. Skips `.memstead/` engine-internal
354/// entries and non-blob nodes. Used by the pre-merge schema-validation
355/// pass `Engine::pull` and `Engine::push` run before they advance the
356/// branch pointer / push to the remote.
357pub type GitBranchReadTreeFn =
358    fn(gitdir: &Path, ref_name: &str) -> Result<Vec<(String, String)>, BackendError>;
359
360/// `Engine::pull` dispatch for git-branch mounts.
361pub type GitBranchPullFn =
362    fn(gitdir: &Path, remote: &str, mem: &str) -> Result<crate::ops::PullOutcome, BackendError>;
363
364/// `Engine::push` dispatch for git-branch mounts.
365pub type GitBranchPushFn = fn(
366    gitdir: &Path,
367    remote: &str,
368    mem: &str,
369    force: bool,
370) -> Result<crate::ops::PushOutcome, BackendError>;
371
372/// `Engine::remote_add` dispatch — configures a named remote on the
373/// mem-repo gitdir (upsert: add, or set-url when it already exists).
374pub type GitBranchRemoteAddFn =
375    fn(gitdir: &Path, name: &str, url: &str) -> Result<crate::ops::RemoteAddOutcome, BackendError>;
376
377/// `Engine::branch_reset` dispatch for git-branch mounts. Returns the
378/// outcome on success; surfaces `BackendError::Other` carrying an
379/// in-band marker (`UNKNOWN_REF:<raw>` or
380/// `PUSHED_COMMITS_PROTECTED:<sha,sha,...>`) the engine layer
381/// un-marshals into typed `EngineError`s.
382pub type GitBranchBranchResetFn = fn(
383    gitdir: &Path,
384    branch: &str,
385    target_sha: &str,
386) -> Result<crate::ops::BranchResetOutcome, BackendError>;
387
388/// Residue-prune dispatch for git-branch mounts.
389/// The `create_mem` orchestrator calls this when
390/// `RecoveryAction::ForceOverwrite` is selected against pre-existing
391/// storage residue. Drops `refs/heads/<branch_full_path>` and the
392/// `__MEMSTEAD:mems/<branch_full_path>/config.json` blob in one
393/// ref-edit transaction (the same call the
394/// `MemBackend::delete_artifacts` impl wraps for delete-files
395/// flows). Surfaces as a function pointer so `memstead-engine` can
396/// drive a prune against an unmounted gitdir without depending on
397/// `memstead-git-branch`.
398pub type GitBranchPruneResidueFn =
399    fn(gitdir: &Path, branch_full_path: &str) -> Result<(), BackendError>;
400
401/// `Engine::install_schema` dispatch for the git-branch backend: write a
402/// schema package (`(relative-path, bytes)` pairs) onto the workspace's
403/// unified `__MEMSTEAD:schemas/<name>@<version>/` ref and return the
404/// resulting commit sha. Mirrors
405/// `memstead_git_branch::storage_memstead::write_schema_to_memstead_ref`.
406pub type GitBranchWriteSchemaFn = fn(
407    gitdir: &Path,
408    name: &str,
409    version: &str,
410    files: &[(String, Vec<u8>)],
411) -> Result<String, BackendError>;
412
413/// Bundle of git-branch-specific op dispatchers. Installed on the
414/// engine at full boot. Each field is one ops-method that previously
415/// lived on the `MemBackend` trait; moving them off the trait keeps
416/// the bytes-level primitive surface clean.
417#[derive(Clone, Copy)]
418pub struct GitBranchOps {
419    pub changes_since: GitBranchChangesSinceFn,
420    pub diff: GitBranchDiffFn,
421    pub branch_reset: GitBranchBranchResetFn,
422    pub fetch: GitBranchFetchFn,
423    pub pull: GitBranchPullFn,
424    pub push: GitBranchPushFn,
425    pub remote_add: GitBranchRemoteAddFn,
426    pub read_tree: GitBranchReadTreeFn,
427    pub export: GitBranchExportFn,
428    pub export_to_bytes: GitBranchExportToBytesFn,
429    pub prune_residue: GitBranchPruneResidueFn,
430    pub write_schema: GitBranchWriteSchemaFn,
431}
432
433impl std::fmt::Debug for Engine {
434    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
435        f.debug_struct("Engine")
436            .field(
437                "mems",
438                &self
439                    .mounts
440                    .iter()
441                    .map(|m| m.mount.mem.as_str())
442                    .collect::<Vec<_>>(),
443            )
444            .finish()
445    }
446}
447
448#[cfg(test)]
449mod in_memory_mem;
450
451#[cfg(test)]
452pub(super) mod test_helpers {
453    use std::io::Write as _;
454    use std::path::{Path, PathBuf};
455
456    use memstead_schema::SchemaRef;
457
458    use crate::backend::MemBackend;
459    use crate::storage::FilesystemMemWriter;
460    use crate::vcs::{Actor, ClientId};
461    use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
462
463    use super::{CreateEntityArgs, CreateEntityOutcome, Engine, RelateEntityArgs};
464
465    use indexmap::IndexMap;
466    use tempfile::TempDir;
467
468    pub(crate) fn pin(name: &str) -> SchemaRef {
469        let version = match name {
470            "default" => semver::Version::new(1, 0, 0),
471            _ => semver::Version::new(0, 1, 0),
472        };
473        SchemaRef::new(name, version)
474    }
475
476    pub(crate) fn folder_mount(mem: &str, path: PathBuf) -> Mount {
477        Mount {
478            mem: mem.to_string(),
479            schema: Some(pin("default")),
480            storage: MountStorage::Folder { path },
481            capability: MountCapability::Write,
482            lifecycle: MountLifecycle::Eager,
483            cross_linkable: true,
484            migration_target: None,
485        }
486    }
487
488    pub(crate) fn in_memory_mount(mem: &str) -> Mount {
489        Mount {
490            mem: mem.to_string(),
491            schema: Some(pin("default")),
492            storage: MountStorage::InMemory,
493            capability: MountCapability::Write,
494            lifecycle: MountLifecycle::Eager,
495            cross_linkable: true,
496            migration_target: None,
497        }
498    }
499
500    pub(crate) fn archive_mount(mem: &str, path: PathBuf) -> Mount {
501        Mount {
502            mem: mem.to_string(),
503            schema: Some(pin("default")),
504            storage: MountStorage::Archive { path },
505            capability: MountCapability::ReadOnly,
506            lifecycle: MountLifecycle::Lazy,
507            cross_linkable: false,
508            migration_target: None,
509        }
510    }
511
512    /// Build a sealed archive at `tmp/<name>.mem` from
513    /// `(relative_path, bytes)` pairs and return the path.
514    pub(crate) fn build_archive(tmp: &Path, name: &str, entries: &[(&str, &[u8])]) -> PathBuf {
515        let path = tmp.join(format!("{name}.mem"));
516        let file = std::fs::File::create(&path).unwrap();
517        let mut writer = zip::ZipWriter::new(file);
518        let opts = zip::write::SimpleFileOptions::default();
519        for (rel, bytes) in entries {
520            writer.start_file(*rel, opts).unwrap();
521            writer.write_all(bytes).unwrap();
522        }
523        writer.finish().unwrap();
524        path
525    }
526
527    /// Write a schema manifest + minimal type bodies under
528    /// `<root>/<name>/`. Each type gets a body with a single
529    /// `body` section and `_default` hierarchy/propagation — enough
530    /// to load and parse markdown that uses that type. Used by tests
531    /// that need a custom schema with shape or vocabulary constraints.
532    pub(crate) fn write_schema_files_with_default_type(
533        root: &Path,
534        name: &str,
535        manifest: &str,
536        types: &[&str],
537    ) {
538        const TYPE_BODY: &str = r#"description: t
539when_to_use: Here
540sections:
541  - key: body
542    heading: Body
543    required: true
544    search_weight: 10.0
545    catch_all: true
546    write_rules: []
547metadata_fields: []
548title_weight: 100.0
549text_fields:
550  - body
551hierarchy_relationship: _default
552propagating_relationships: []
553updatable_fields:
554  - title
555  - body
556health_required_fields:
557  - body
558staleness_threshold_days: 90
559write_rules: []
560"#;
561        let dir = root.join(name);
562        std::fs::create_dir_all(dir.join("types")).unwrap();
563        std::fs::write(dir.join("schema.yaml"), manifest).unwrap();
564        for type_name in types {
565            let body = format!("name: {type_name}\n{TYPE_BODY}");
566            std::fs::write(dir.join("types").join(format!("{type_name}.yaml")), body).unwrap();
567        }
568    }
569
570    pub(crate) fn empty_create_args(mem: &str, title: &str) -> CreateEntityArgs {
571        // The
572        // create path refuses on missing required sections. The
573        // default `spec` type requires `identity` + `purpose`. Seed
574        // both with a single space so the test fixture remains a
575        // valid creation request — every test that uses this helper
576        // as a fixture builder continues to work, and tests that
577        // specifically exercise the refusal supply an explicit
578        // empty-sections payload (see the dedicated refusal tests).
579        let mut sections = IndexMap::new();
580        sections.insert("identity".to_string(), "fixture identity body".to_string());
581        sections.insert("purpose".to_string(), "fixture purpose body".to_string());
582        CreateEntityArgs {
583            mem: mem.to_string(),
584            title: title.to_string(),
585            entity_type: "spec".to_string(),
586            sections,
587            metadata: IndexMap::new(),
588            relations: Vec::new(),
589            dry_run: false,
590        }
591    }
592
593    pub(crate) fn cli_actor() -> (Actor, ClientId) {
594        (
595            Actor::Cli,
596            ClientId {
597                name: "claude-code".to_string(),
598                version: "2.1.0".to_string(),
599            },
600        )
601    }
602
603    pub(crate) fn engine_with_seed(tmp: &TempDir, title: &str) -> (Engine, CreateEntityOutcome) {
604        let mem_dir = tmp.path().to_path_buf();
605        let writer = FilesystemMemWriter::new(mem_dir.clone());
606        let mut engine = Engine::from_mounts(vec![(
607            folder_mount("specs", mem_dir),
608            Box::new(writer) as Box<dyn MemBackend>,
609        )])
610        .unwrap();
611        let (actor, client) = cli_actor();
612        let outcome = engine
613            .create_entity(
614                empty_create_args("specs", title),
615                actor,
616                Some(&client),
617                None,
618            )
619            .unwrap();
620        (engine, outcome)
621    }
622    pub(crate) fn build_demo_engine(tmp: &TempDir) -> Engine {
623        let mem_dir = tmp.path().to_path_buf();
624        let writer = FilesystemMemWriter::new(mem_dir.clone());
625        let mut engine = Engine::from_mounts(vec![(
626            folder_mount("specs", mem_dir),
627            Box::new(writer) as Box<dyn MemBackend>,
628        )])
629        .unwrap();
630        let (actor, client) = cli_actor();
631        let source = engine
632            .create_entity(
633                empty_create_args("specs", "Source One"),
634                actor,
635                Some(&client),
636                None,
637            )
638            .unwrap();
639        let target = engine
640            .create_entity(
641                empty_create_args("specs", "Target Two"),
642                actor,
643                Some(&client),
644                None,
645            )
646            .unwrap();
647        engine
648            .create_entity(
649                empty_create_args("specs", "Lonely Three"),
650                actor,
651                Some(&client),
652                None,
653            )
654            .unwrap();
655        engine
656            .relate_entity(
657                RelateEntityArgs {
658                    source: source.id.clone(),
659                    expected_hash: Some(source.content_hash.clone()),
660                    rel_type: "USES".to_string(),
661                    target: target.id.clone(),
662                    remove: false,
663                    description: None,
664                },
665                actor,
666                Some(&client),
667                None,
668            )
669            .unwrap();
670        engine
671    }
672}