Skip to main content

memstead_cli/
setup.rs

1//! Engine setup from global CLI flags. Produces an `Engine`
2//! synchronously (no tokio) for the CLI to call into directly.
3//!
4//! Post-rebuild there is one workspace marker: `.memstead/workspace.toml`
5//! at the workspace root. The `mem-repo` Cargo feature decides
6//! which engine factory consumes it — full routes through
7//! [`memstead_git_branch::workspace_store::engine_from_workspace_root`]
8//! (git-branch backends plus folder + archive), lean routes through
9//! [`memstead_base::Engine::from_workspace_root`] (folder + archive
10//! only).
11//!
12//! [`CliEngine`] wraps either flavour; subcommands match-dispatch on
13//! it. The `WorkspaceShape` variant is retained so the lean build
14//! can still surface an actionable "this is the lean binary, your
15//! workspace has git-branch mounts" error when the operator points a
16//! lean binary at a full workspace — the shape tag is derived from
17//! `mem-repo/.git` co-existing with the marker rather than the
18//! marker itself.
19
20use std::path::{Path, PathBuf};
21
22#[cfg(feature = "mem-repo")]
23use anyhow::Context;
24
25use memstead_base::Engine as BaseEngine;
26use memstead_base::vcs::ClientId;
27#[cfg(feature = "mem-repo")]
28use memstead_base::vcs::{Actor, CommitContext};
29#[cfg(feature = "mem-repo")]
30use memstead_git_branch::workspace_store::engine_from_workspace_root;
31
32use crate::CliError;
33use crate::output::ExitKind;
34
35/// Structured-code constant for the missing-workspace exit envelope.
36/// Surfaced on both `--json` output (under the `code` key in
37/// `details`) and as the `Display` body of the underlying `CliError`.
38/// Scripts and agents branch on this stable token; the human prose
39/// (which mentions the recovery command) is the message and can be
40/// adjusted without breaking the contract.
41pub const WORKSPACE_NOT_INITIALISED_CODE: &str = "WORKSPACE_NOT_INITIALISED";
42
43/// Recovery command suggested when no `.memstead/workspace.toml` is
44/// reachable from cwd. `memstead mem-repo init` in the full build (this
45/// binary speaks mem-repo); `memstead init` in the lean build. The
46/// structured `hint.recovery_command` field carries this token
47/// verbatim so an agent can re-exec it.
48#[cfg(feature = "mem-repo")]
49pub const WORKSPACE_RECOVERY_COMMAND: &str = "memstead mem-repo init";
50#[cfg(not(feature = "mem-repo"))]
51pub const WORKSPACE_RECOVERY_COMMAND: &str = "memstead init";
52
53/// Build the typed `WORKSPACE_NOT_INITIALISED` exit envelope. Goes
54/// through `CliError` so the top-level `main` downcast lifts the
55/// `code` + `hint` fields into the JSON output.
56pub fn workspace_not_initialised_error(message: &str) -> CliError {
57    CliError {
58        kind: ExitKind::Generic,
59        code: WORKSPACE_NOT_INITIALISED_CODE,
60        message: message.to_string(),
61        details: Some(serde_json::json!({
62            "hint": { "recovery_command": WORKSPACE_RECOVERY_COMMAND },
63        })),
64    }
65}
66
67/// Lift a [`memstead_base::BootError`] into the typed CLI envelope.
68/// The boot seam previously flattened these through `anyhow`, so the
69/// `main` downcast missed them and every boot failure surfaced as
70/// `code: INTERNAL` with no next step (plenum 2026-08-06/07, expertise
71/// 2026-08-07). The typed material lives on
72/// [`memstead_base::BootError::code`]; this function only wraps it in
73/// the CLI's exit shape. The message is
74/// [`memstead_base::BootError::surface_message`] verbatim — identical
75/// on the MCP server's boot diagnostics for the same broken workspace.
76pub fn boot_error_to_cli(workspace_root: &Path, e: memstead_base::BootError) -> CliError {
77    let details = e.details();
78    let details = match &details {
79        serde_json::Value::Object(map) if map.is_empty() => None,
80        _ => Some(details),
81    };
82    CliError {
83        kind: ExitKind::Generic,
84        code: e.code(),
85        message: e.surface_message(workspace_root),
86        details,
87    }
88}
89
90/// Global CLI state: shared flags + a lazily-initialized `Engine`.
91pub struct CliContext {
92    pub json: bool,
93    /// User asked for quiet stderr (`--quiet`). The CLI runs the
94    /// engine in-process and never installs a `tracing_subscriber`,
95    /// so the flag is informational.
96    pub quiet: bool,
97    /// The invocation-level declared role (`--role`, agent-trust
98    /// plan 13), already validated at parse time. Stamped onto every
99    /// engine this context constructs so mutations record it.
100    pub role: memstead_base::vcs::Role,
101    /// The invocation-level declared identity (`--identity` /
102    /// `MEMSTEAD_IDENTITY`, agent-trust plan 15), already normalised
103    /// and length-checked at parse time. Stamped onto every engine
104    /// this context constructs so mutations and checks record it.
105    pub identity: Option<String>,
106}
107
108/// Workspace flavour resolved from cwd. Subcommands dispatch on this
109/// to pick the right engine accessor.
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub enum WorkspaceShape {
112    /// Mem-repo workspace — multi-mem, git-backed.
113    /// The `.memstead/workspace.toml` root also carries `mem-repo/.git/`.
114    MemRepo,
115    /// Filesystem-mem workspace — single-mem, history-free.
116    /// The `.memstead/workspace.toml` root has no `mem-repo/.git/`.
117    Filesystem,
118}
119
120/// Render a string as one POSIX shell word. Bare when every character
121/// is safe unquoted; otherwise single-quoted, with embedded `'` closed
122/// and re-opened the POSIX way (`'\''`).
123///
124/// A leading `-` forces quoting even though `-` is otherwise safe: an
125/// argument that starts with a dash is read as an option by whatever
126/// receives it. (Quoting alone does not save `cd`, which parses its
127/// argument after the shell strips quotes — callers printing a `cd`
128/// emit `cd --`.)
129///
130/// Lives here rather than beside its first caller because every message
131/// that interpolates a filesystem path into a command the reader is
132/// expected to run needs it, and the one that did not — the shape
133/// disclosure's other-shape command — was unrunnable for anyone whose
134/// binary path contained a space.
135pub fn shell_quote(value: &str) -> String {
136    let safe = |c: char| c.is_ascii_alphanumeric() || "._-/@:+,=".contains(c);
137    if !value.is_empty() && !value.starts_with('-') && value.chars().all(safe) {
138        return value.to_string();
139    }
140    format!("'{}'", value.replace('\'', r"'\''"))
141}
142
143/// The running binary, resolved and shell-quoted — the form to
144/// interpolate into any command a message tells the reader to run.
145fn memstead_word() -> String {
146    shell_quote(&memstead_program())
147}
148
149/// The `UNSUPPORTED_WORKSPACE_SHAPE` refusal, in one place because both
150/// mem-repo-only gates mint it and they must not drift. Names the
151/// recovering command and the verbs that do work here, both resolved to
152/// this binary — the refusal is read by someone who is about to type
153/// what it says.
154///
155/// Both gates that mint it are mem-repo-only, so the lean build never
156/// reaches this refusal (it has no mem-repo-only subcommand to refuse).
157#[cfg(feature = "mem-repo")]
158fn unsupported_workspace_shape_message() -> String {
159    let m = memstead_word();
160    format!(
161        "this subcommand is mem-repo-only and not yet supported on filesystem-mem workspaces — \
162         bootstrap one with `{m} mem-repo init` in a fresh folder, or use `{m} status` / \
163         `{m} list` / `{m} search` / `{m} entity` / `{m} health` / \
164         `{m} create|update|delete|relate|rename` here instead."
165    )
166}
167
168/// Resolve the running `memstead` binary to something the reader can
169/// actually type. Bare `memstead` when that name on `PATH` resolves to
170/// this very binary; otherwise the path we were invoked as.
171///
172/// A reader who ran `./target/debug/memstead`, or an unpacked download,
173/// or a binary under a versioned directory, has no `memstead` on
174/// `PATH` — and every printed command naming a bare `memstead` fails
175/// for them with `command not found`. Every message that tells someone
176/// to run this binary goes through here.
177pub fn memstead_program() -> String {
178    let Ok(exe) = std::env::current_exe() else {
179        return "memstead".to_string();
180    };
181    let canonical_exe = exe.canonicalize().unwrap_or_else(|_| exe.clone());
182    if let Some(paths) = std::env::var_os("PATH") {
183        for dir in std::env::split_paths(&paths) {
184            let candidate = dir.join("memstead");
185            if candidate.is_file() && candidate.canonicalize().is_ok_and(|c| c == canonical_exe) {
186                return "memstead".to_string();
187            }
188        }
189    }
190    exe.display().to_string()
191}
192
193/// The command that produces the *other* shape than the one a
194/// disclosure is describing. Feature-gated because every command a
195/// message names must exist in the binary that prints it: the lean
196/// build has no `mem-repo` subcommand group, so it points at the full
197/// build rather than at a verb it would reject. The program name is
198/// resolved rather than hardcoded, for the same reason the verify
199/// commands resolve it — this is an instruction, not a mention.
200#[cfg(feature = "mem-repo")]
201fn mem_repo_init_hint() -> String {
202    format!("`{} mem-repo init` in a fresh folder", memstead_word())
203}
204#[cfg(not(feature = "mem-repo"))]
205fn mem_repo_init_hint() -> String {
206    "the full build of memstead (this lean build has no `mem-repo` subcommand), then \
207     `memstead mem-repo init` in a fresh folder"
208        .to_string()
209}
210
211/// What a filesystem-mem workspace cannot do — stated with the same
212/// feature gate as the hint above, and for the same reason. The full
213/// build names `memstead install`, which exists there and refuses by
214/// shape; the lean build has no `install` subcommand at all, so naming
215/// it would send the reader to a verb that does not parse. The lean
216/// wording states the limit without borrowing a command it lacks.
217#[cfg(feature = "mem-repo")]
218const FILESYSTEM_CANNOT: &str = "**It cannot install mems from the registry.** `memstead install \
219     <scope>/<name>` (and the other mem-repo-only subcommands) refuse here with \
220     `UNSUPPORTED_WORKSPACE_SHAPE`.";
221#[cfg(not(feature = "mem-repo"))]
222const FILESYSTEM_CANNOT: &str = "**It cannot install mems from the registry, and holds exactly \
223     one mem.** The subcommands that do either are mem-repo-only, and this lean build does not \
224     carry them at all.";
225
226impl WorkspaceShape {
227    /// Resolve the shape of an existing workspace root. Routes through
228    /// the engine's shared probe so the CLI, the refusals, and the MCP
229    /// boot line can never disagree about the same directory.
230    pub fn at(workspace_root: &Path) -> Self {
231        if memstead_base::is_mem_repo_shaped(workspace_root) {
232            WorkspaceShape::MemRepo
233        } else {
234            WorkspaceShape::Filesystem
235        }
236    }
237
238    /// The one spelling of this shape, shared with the engine.
239    pub fn label(self) -> &'static str {
240        match self {
241            WorkspaceShape::MemRepo => "mem-repo",
242            WorkspaceShape::Filesystem => "filesystem-mem",
243        }
244    }
245}
246
247/// The three-part disclosure a workspace-creating command owes its
248/// caller: which shape was just made, one concrete thing that shape
249/// cannot do, and the exact command that produces the other one.
250///
251/// Held as parts rather than pre-rendered prose because both receipts
252/// carry it: the markdown block a human reads, and the `--json`
253/// envelope an agent reads. A label alone on the machine surface would
254/// name the fork without disclosing it, which is the failure this whole
255/// disclosure exists to end — so both renderings come from one value.
256pub struct ShapeDisclosure {
257    /// The shape just created.
258    pub shape: WorkspaceShape,
259    /// One sentence on what this shape is.
260    pub summary: String,
261    /// One concrete thing this shape cannot do, in markdown.
262    pub cannot: &'static str,
263    /// The shape a caller would get instead.
264    pub other_shape: WorkspaceShape,
265    /// The exact command producing [`Self::other_shape`], in markdown.
266    pub other_shape_command: String,
267}
268
269/// The disclosure for a shape.
270///
271/// `quickstart`, `init`, and `mem-repo init` all print this — the
272/// disclosure is symmetric, not a warning bolted onto one branch. It
273/// belongs in the creating command's own receipt because that is the
274/// moment the fork is decided and the output the newcomer is already
275/// reading; a sentence elsewhere (the `install --help` clause)
276/// demonstrably arrives after the workspace exists.
277pub fn shape_disclosure(shape: WorkspaceShape) -> ShapeDisclosure {
278    shape_disclosure_in(shape, None)
279}
280
281/// The disclosure for a shape whose mem folder is `mem_folder` — a
282/// workspace-relative folder name when the mem does not own the
283/// workspace root (the guided `quickstart --repo` layout), `None` for
284/// the collapsed shape every other front door creates.
285///
286/// The parameter exists because the filesystem shape's summary makes a
287/// claim about *where the files are*, and that claim is the reader's
288/// first check: pointing them at "this folder" when their entities live
289/// one folder down would be untrue in exactly the receipt that has to
290/// be trusted.
291pub fn shape_disclosure_in(shape: WorkspaceShape, mem_folder: Option<&str>) -> ShapeDisclosure {
292    match shape {
293        WorkspaceShape::Filesystem => ShapeDisclosure {
294            shape,
295            summary: match mem_folder {
296                None => "One mem, plain `.md` files in this folder, no git history — nothing \
297                         else to set up."
298                    .to_string(),
299                Some(folder) => format!(
300                    "One mem, plain `.md` files in `{folder}/` — that folder is the whole \
301                     graph, and Memstead keeps no history of its own for it."
302                ),
303            },
304            cannot: FILESYSTEM_CANNOT,
305            other_shape: WorkspaceShape::MemRepo,
306            other_shape_command: format!(
307                "**The other shape** — mem-repo: many mems, git-backed, registry-capable — \
308                 comes from {hint}. Switching later means starting a second \
309                 workspace, so decide now if you intend to install mems.",
310                hint = mem_repo_init_hint(),
311            ),
312        },
313        WorkspaceShape::MemRepo => ShapeDisclosure {
314            shape,
315            summary: "Many mems on git branches, full history — every subcommand works here, \
316                      including `memstead install <scope>/<name>`."
317                .to_string(),
318            cannot: "**It costs a git repository.** The mems live in `mem-repo/.git/` and \
319                     every mutation is a commit — not a folder of files you can hand-edit.",
320            other_shape: WorkspaceShape::Filesystem,
321            other_shape_command: format!(
322                "**The other shape** — filesystem-mem: one mem, plain `.md` files, no git — \
323                 comes from `{} quickstart` in a fresh folder.",
324                memstead_word(),
325            ),
326        },
327    }
328}
329
330impl ShapeDisclosure {
331    /// The markdown block for a human-facing receipt.
332    pub fn lines(&self) -> Vec<String> {
333        vec![
334            format!("## Workspace shape: {}", self.shape.label()),
335            String::new(),
336            self.summary.clone(),
337            String::new(),
338            format!("- {}", self.cannot),
339            format!("- {}", self.other_shape_command),
340        ]
341    }
342
343    /// The same three parts for a `--json` receipt. The agent surface
344    /// gets the limit and the recovering command, not just the label.
345    pub fn to_json(&self) -> serde_json::Value {
346        serde_json::json!({
347            "shape": self.shape.label(),
348            "summary": self.summary.clone(),
349            "cannot": self.cannot,
350            "other_shape": self.other_shape.label(),
351            "other_shape_command": self.other_shape_command,
352        })
353    }
354}
355
356/// Convenience for callers that only render markdown.
357pub fn shape_disclosure_lines(shape: WorkspaceShape) -> Vec<String> {
358    shape_disclosure(shape).lines()
359}
360
361/// [`shape_disclosure_lines`] for a mem that lives in its own folder.
362pub fn shape_disclosure_lines_in(shape: WorkspaceShape, mem_folder: Option<&str>) -> Vec<String> {
363    shape_disclosure_in(shape, mem_folder).lines()
364}
365
366/// Engine instance + the workspace flavour it serves. Subcommands
367/// match on the variant to call the right engine API; the read-side
368/// store accessor (`engine.store()`) lives on both flavours so simple
369/// read commands can share most of their bodies.
370///
371/// The `MemRepo` variant is only present under the `mem-repo`
372/// feature. In the lean build (`--no-default-features`) the enum
373/// collapses to a single `Filesystem` arm — every subcommand's
374/// dispatch elides the missing arm via `cfg`.
375pub enum CliEngine {
376    #[cfg(feature = "mem-repo")]
377    MemRepo(BaseEngine),
378    /// Filesystem-mem flavour, served by the unified [`memstead_base::Engine`].
379    Filesystem(BaseEngine),
380}
381
382impl CliEngine {
383    /// The unified base engine behind whichever flavour booted. Both
384    /// variants wrap [`BaseEngine`]; commands that treat the flavours
385    /// identically destructure here instead of carrying a per-site
386    /// match (which, in the lean build's single-variant enum, is the
387    /// `infallible_destructuring_match` shape the isolated lean clippy
388    /// leg flags).
389    pub fn base(&self) -> &BaseEngine {
390        #[cfg(feature = "mem-repo")]
391        {
392            match self {
393                CliEngine::MemRepo(e) => e,
394                CliEngine::Filesystem(e) => e,
395            }
396        }
397        #[cfg(not(feature = "mem-repo"))]
398        {
399            let CliEngine::Filesystem(e) = self;
400            e
401        }
402    }
403
404    /// Mutable twin of [`Self::base`].
405    pub fn base_mut(&mut self) -> &mut BaseEngine {
406        #[cfg(feature = "mem-repo")]
407        {
408            match self {
409                CliEngine::MemRepo(e) => e,
410                CliEngine::Filesystem(e) => e,
411            }
412        }
413        #[cfg(not(feature = "mem-repo"))]
414        {
415            let CliEngine::Filesystem(e) = self;
416            e
417        }
418    }
419
420    /// Owning twin of [`Self::base`].
421    pub fn into_base(self) -> BaseEngine {
422        #[cfg(feature = "mem-repo")]
423        {
424            match self {
425                CliEngine::MemRepo(e) => e,
426                CliEngine::Filesystem(e) => e,
427            }
428        }
429        #[cfg(not(feature = "mem-repo"))]
430        {
431            let CliEngine::Filesystem(e) = self;
432            e
433        }
434    }
435}
436
437impl CliContext {
438    /// Resolve the workspace flavour by walking up from cwd. Returns
439    /// `None` when no `.memstead/workspace.toml` is found in any ancestor.
440    ///
441    /// Post-rebuild the marker is shape-neutral — the same
442    /// `.memstead/workspace.toml` carries both folder-only workspaces and
443    /// mem-repo workspaces. The flavour tag comes from whether the
444    /// workspace root also carries `mem-repo/.git/` (mem-repo
445    /// flavour) or not (folder-only flavour). The lean CLI uses this
446    /// distinction to surface "this is the lean binary" when the
447    /// operator points it at a workspace with git-branch mounts.
448    pub fn workspace_shape(&self) -> Option<(WorkspaceShape, PathBuf)> {
449        let cwd = std::env::current_dir().ok()?;
450        let root = find_workspace_root(&cwd)?;
451        Some((WorkspaceShape::at(&root), root))
452    }
453
454    /// Build a [`CliEngine`] from the current cwd. The workspace
455    /// marker `.memstead/workspace.toml` resolves either flavour; the
456    /// presence of `mem-repo/.git/` switches the engine factory.
457    ///
458    /// On the lean build (`--no-default-features`) the mem-repo
459    /// branch surfaces a clear "not built into this binary" error so
460    /// a user pointing the lean build at a mem-repo workspace
461    /// gets an actionable signal rather than a confusing "no
462    /// workspace" bail.
463    pub fn cli_engine(&self) -> anyhow::Result<CliEngine> {
464        match self.workspace_shape() {
465            Some((_, root)) => self.cli_engine_at(&root),
466            None => Err(workspace_not_initialised_error(
467                "No workspace found. Run from a directory containing `.memstead/workspace.toml` (run `memstead init` for a folder-mount workspace, or `memstead mem-repo init` for a mem-repo workspace).",
468            )
469            .into()),
470        }
471    }
472
473    /// [`Self::cli_engine`] with the lazy-mount load scoped to ONE mem:
474    /// deferred (lazy, not-yet-loaded) mems other than `mem` stay
475    /// unloaded, so a cold command that touches only this mem pays only
476    /// its load — the cold-path cut the sizing curve names. Only for
477    /// commands whose ENTIRE answer is computable from the named mem's
478    /// slice of the store (plus mount metadata): anything that renders
479    /// cross-mem state — incoming edges, workspace-wide counts, search
480    /// without a mem filter — must use [`Self::cli_engine`], whose
481    /// full load keeps every answer computed over a complete store.
482    /// Engine mutations need no caller-side scoping either way: each
483    /// runs the `reload_if_stale` funnel for its target mem itself, and
484    /// the ones whose guards read cross-mem state take the full load
485    /// themselves (delete's incoming-refs guards, relate's two
486    /// endpoints).
487    pub fn cli_engine_scoped(&self, mem: &str) -> anyhow::Result<CliEngine> {
488        match self.workspace_shape() {
489            Some((_, root)) => {
490                let mut engine = self.cli_engine_at_unloaded(&root)?;
491                match &mut engine {
492                    #[cfg(feature = "mem-repo")]
493                    CliEngine::MemRepo(e) => e.ensure_mems_loaded(Some(mem)),
494                    CliEngine::Filesystem(e) => e.ensure_mems_loaded(Some(mem)),
495                }
496                Ok(engine)
497            }
498            None => Err(workspace_not_initialised_error(
499                "No workspace found. Run from a directory containing `.memstead/workspace.toml` (run `memstead init` for a folder-mount workspace, or `memstead mem-repo init` for a mem-repo workspace).",
500            )
501            .into()),
502        }
503    }
504
505    /// Build a [`CliEngine`] rooted at an explicit workspace directory,
506    /// skipping the cwd walk-up. The flavour is still derived from
507    /// whether `<root>/mem-repo/.git/` is present, so callers that
508    /// already know the root (e.g. `memstead publish --workspace`) get
509    /// the same factory selection as [`Self::cli_engine`]. The split
510    /// also gives subcommands a chdir-free, unit-testable engine seam.
511    pub fn cli_engine_at(&self, root: &Path) -> anyhow::Result<CliEngine> {
512        let mut engine = self.cli_engine_at_unloaded(root)?;
513        // Default lazy-mount posture (flywheel W7/01): the CLI loads
514        // every deferred mem up front, so a one-shot command behaves
515        // byte-identically to the all-eager world — no answer computes
516        // over a partial store. Commands whose whole answer lives in one
517        // mem opt into [`Self::cli_engine_scoped`] instead.
518        match &mut engine {
519            #[cfg(feature = "mem-repo")]
520            CliEngine::MemRepo(e) => e.ensure_mems_loaded(None),
521            CliEngine::Filesystem(e) => e.ensure_mems_loaded(None),
522        }
523        Ok(engine)
524    }
525
526    /// The boot half of [`Self::cli_engine_at`]: flavour detection and
527    /// engine construction, with NO deferred-mem load — every caller
528    /// decides the load scope explicitly (full for the correct-by-
529    /// default path, one mem for the scoped path).
530    fn cli_engine_at_unloaded(&self, root: &Path) -> anyhow::Result<CliEngine> {
531        if memstead_base::is_mem_repo_shaped(root) {
532            #[cfg(feature = "mem-repo")]
533            {
534                let mut engine =
535                    engine_from_workspace_root(root).map_err(|e| boot_error_to_cli(root, e))?;
536                engine.set_role(self.role);
537                engine.set_identity(self.identity.clone());
538                return Ok(CliEngine::MemRepo(engine));
539            }
540            #[cfg(not(feature = "mem-repo"))]
541            {
542                return Err(CliError {
543                    kind: ExitKind::Generic,
544                    code: "UNSUPPORTED_WORKSPACE_SHAPE",
545                    message:
546                        "this is the lean build of memstead (folder-mount only); the workspace is mem-repo-shaped (`mem-repo/.git/` present). Install the full build (`cargo build --features mem-repo`) or run from a workspace whose mounts are all folder-backed."
547                            .to_string(),
548                    details: None,
549                }
550                .into());
551            }
552        }
553        let mut engine =
554            BaseEngine::from_workspace_root(root).map_err(|e| boot_error_to_cli(root, e))?;
555        engine.set_role(self.role);
556        engine.set_identity(self.identity.clone());
557        Ok(CliEngine::Filesystem(engine))
558    }
559
560    /// Build the unified [`memstead_base::Engine`] for a mem-repo-shaped
561    /// workspace. Delegates to `engine_from_workspace_root` which
562    /// handles layout detection, mount enumeration, schema resolution,
563    /// and readMems hydration in one pass.
564    ///
565    /// Only compiled into the full build — the lean build never sees a
566    /// mem-repo workspace because `cli_engine()` rejects it before
567    /// reaching here.
568    #[cfg(feature = "mem-repo")]
569    pub fn engine(&self) -> anyhow::Result<BaseEngine> {
570        let cwd = std::env::current_dir().context("Could not determine current directory")?;
571
572        let Some(root) = find_workspace_root(&cwd) else {
573            return Err(workspace_not_initialised_error(
574                "No workspace found. Run from a directory containing `.memstead/workspace.toml` (run `memstead mem-repo init` to bootstrap).",
575            )
576            .into());
577        };
578
579        // Subcommands routed through `engine()` (rather than
580        // `cli_engine()`) require mem-repo shape — they read /
581        // write commit-shaped artefacts (`workspace dump` snapshots,
582        // `batch-update` commit envelopes) that have no analogue on a
583        // folder-mount-only workspace. Surface the mem-repo-only
584        // tag here so callers print an actionable message instead of
585        // booting into a foldery engine and erroring later.
586        if !memstead_base::is_mem_repo_shaped(&root) {
587            return Err(CliError {
588                kind: ExitKind::Generic,
589                code: "UNSUPPORTED_WORKSPACE_SHAPE",
590                message: unsupported_workspace_shape_message(),
591                details: None,
592            }
593            .into());
594        }
595
596        let mut engine =
597            engine_from_workspace_root(&root).map_err(|e| boot_error_to_cli(&root, e))?;
598        engine.set_role(self.role);
599        engine.set_identity(self.identity.clone());
600        // Same interim lazy-mount posture as `cli_engine_at`.
601        engine.ensure_mems_loaded(None);
602        Ok(engine)
603    }
604}
605
606/// Walk upward from `start` looking for the first ancestor that
607/// contains `.memstead/workspace.toml` (the post-rebuild workspace
608/// marker). Returns the first ancestor directory carrying the marker,
609/// or `None` if the walk reaches filesystem root without finding one.
610///
611/// Both files and directories are accepted as `start`. A plain file's
612/// parent is used as the first candidate; for a directory, the
613/// directory itself is the first candidate.
614///
615/// Deeper-marker semantics: because the walk is upward and stops at
616/// the first match, an inner workspace nested inside an outer one
617/// resolves to the inner.
618///
619/// Mirrors `memstead-mcp/src/main.rs::find_workspace_root` and the
620/// per-command walkers in `memstead-cli/src/commands/link.rs` /
621/// `memstead-cli/src/commands/publish.rs`. Keep the resolution rules in
622/// sync if any of these change.
623pub fn find_workspace_root(start: &Path) -> Option<PathBuf> {
624    let mut cursor: PathBuf = if start.is_dir() {
625        start.to_path_buf()
626    } else {
627        start.parent()?.to_path_buf()
628    };
629    loop {
630        if memstead_base::is_workspace_root(&cursor) {
631            return Some(cursor);
632        }
633        let parent = cursor.parent()?;
634        if parent == cursor {
635            return None;
636        }
637        cursor = parent.to_path_buf();
638    }
639}
640
641/// Compatibility alias for `find_workspace_root` — kept so existing
642/// CLI subcommands (export, changes, …) that historically routed
643/// through the lean-flavour walker continue to compile. Both walkers
644/// now find the same marker; the alias is intentional for
645/// call-site clarity (`find_workspace_root` reads as the canonical
646/// surface; `find_filesystem_workspace_root` documents the
647/// folder-mount-only intent of its caller).
648pub fn find_filesystem_workspace_root(start: &Path) -> Option<PathBuf> {
649    find_workspace_root(start)
650}
651
652/// Provenance bundle for every CLI-initiated mutation. `Actor::Cli` +
653/// `memstead-cli@<CARGO_PKG_VERSION>`. The `Tool:` trailer stays `None`: CLI
654/// subcommands aren't MCP tools and the commit subject (`memstead: create …`)
655/// already carries the action verb — a second taxonomy would drift.
656///
657/// Only used by mem-repo write paths today; filesystem-mem write
658/// paths assemble their own provenance directly. The function therefore
659/// only compiles when `mem-repo` is enabled.
660#[cfg(feature = "mem-repo")]
661pub fn cli_ctx() -> CommitContext<'static> {
662    cli_ctx_with_note(None)
663}
664
665/// The `memstead-cli@<version>` client identity stamped into the commit
666/// body's `Client:` provenance trailer. Shared by every CLI mutation
667/// path so the trailer is uniform across `create` / `update` / `relate`
668/// / `rename`. Un-gated (unlike [`cli_ctx_with_note`]) because the
669/// `relate` path passes the client to `relate_entity` directly rather
670/// than through a `CommitContext`, and that path compiles on both
671/// flavours.
672pub fn cli_client_id() -> ClientId {
673    ClientId {
674        name: "memstead-cli".to_string(),
675        version: env!("CARGO_PKG_VERSION").to_string(),
676    }
677}
678
679/// Provenance bundle carrying an optional agent-authored `--note`.
680/// The note rides into the same payload slot the MCP `note` parameter
681/// uses; the engine's `require_notes` policy gate fires `NOTE_MISSING`
682/// symmetrically across both surfaces.
683#[cfg(feature = "mem-repo")]
684pub fn cli_ctx_with_note(note: Option<String>) -> CommitContext<'static> {
685    CommitContext {
686        actor: Actor::Cli,
687        client: Some(cli_client_id()),
688        tool: None,
689        note,
690        role: Default::default(),
691        identity: None,
692        logical_operation_id: None,
693        entity_ids: None,
694    }
695}
696
697/// Build the unified [`memstead_base::Engine`] for a mem-repo-shaped
698/// workspace. Delegates to `engine_from_workspace_root` which
699/// handles layout detection, mount enumeration, schema resolution,
700/// and readMems hydration in one pass.
701///
702/// Subcommands routed through this helper require mem-repo shape —
703/// they read / write commit-shaped artefacts (`workspace dump`
704/// snapshots, `batch-update` commit envelopes) that have no analogue
705/// on a folder-mount-only workspace.
706#[cfg(feature = "mem-repo")]
707pub fn full_engine(_ctx: &CliContext) -> anyhow::Result<BaseEngine> {
708    // Typed, not INTERNAL: an unreadable or deleted working directory
709    // is an environment condition the caller can act on (`cd` somewhere
710    // that exists), and no leaf of a user-triggerable command may
711    // collapse into the generic sentinel.
712    let cwd = std::env::current_dir().map_err(|e| {
713        CliError::new(
714            ExitKind::Generic,
715            "INTERNAL_IO_ERROR",
716            format!("could not determine the current directory ({e}) — run from a directory that exists and is readable"),
717        )
718    })?;
719
720    let Some(root) = find_workspace_root(&cwd) else {
721        return Err(workspace_not_initialised_error(
722            "No workspace found. Run from a directory containing `.memstead/workspace.toml` (run `memstead mem-repo init` to bootstrap).",
723        )
724        .into());
725    };
726
727    if !memstead_base::is_mem_repo_shaped(&root) {
728        return Err(CliError {
729            code: "UNSUPPORTED_WORKSPACE_SHAPE",
730            kind: ExitKind::Generic,
731            message: unsupported_workspace_shape_message(),
732            details: None,
733        }
734        .into());
735    }
736
737    let mut engine = engine_from_workspace_root(&root).map_err(|e| boot_error_to_cli(&root, e))?;
738    engine.set_role(_ctx.role);
739    engine.set_identity(_ctx.identity.clone());
740    // Same CLI lazy-mount posture as `cli_engine_at`/`engine()`: load
741    // every deferred mem up front, so no consumer of this seam (`mem
742    // list` counts, `recover`, the batch commands, install/uninstall)
743    // computes an answer over a partial store. `full_engine` names the
744    // FullEngine flavour, not this posture — without this call an
745    // unloaded lazy mem rendered as entity count 0 (fifth lazy-mount
746    // grade).
747    engine.ensure_mems_loaded(None);
748    Ok(engine)
749}
750
751#[cfg(test)]
752mod tests {
753    use super::*;
754    use tempfile::TempDir;
755
756    fn touch_marker(ws: &std::path::Path) {
757        std::fs::create_dir_all(ws.join(".memstead")).unwrap();
758        std::fs::write(ws.join(".memstead").join("workspace.toml"), "").unwrap();
759    }
760
761    #[test]
762    fn find_workspace_root_walks_up_to_marker() {
763        let tmp = TempDir::new().unwrap();
764        let ws = tmp.path().join("ws");
765        let nested = ws.join("a").join("b").join("specs");
766        std::fs::create_dir_all(&nested).unwrap();
767        touch_marker(&ws);
768        let found =
769            find_workspace_root(&nested).expect("walk should find .memstead/workspace.toml");
770        assert_eq!(found.canonicalize().unwrap(), ws.canonicalize().unwrap());
771    }
772
773    #[test]
774    fn find_workspace_root_returns_none_when_absent() {
775        let tmp = TempDir::new().unwrap();
776        let nested = tmp.path().join("a").join("b");
777        std::fs::create_dir_all(&nested).unwrap();
778        assert!(find_workspace_root(&nested).is_none());
779    }
780
781    #[test]
782    fn find_workspace_root_stops_at_containing_dir() {
783        let tmp = TempDir::new().unwrap();
784        let ws = tmp.path().join("ws");
785        std::fs::create_dir_all(&ws).unwrap();
786        touch_marker(&ws);
787        let found = find_workspace_root(&ws).expect("ws itself carries .memstead/workspace.toml");
788        assert_eq!(found, ws);
789    }
790
791    #[test]
792    fn find_workspace_root_accepts_file_start() {
793        let tmp = TempDir::new().unwrap();
794        let ws = tmp.path().join("ws");
795        std::fs::create_dir_all(&ws).unwrap();
796        touch_marker(&ws);
797        let file = ws.join("some-file.md");
798        std::fs::write(&file, "").unwrap();
799        let found = find_workspace_root(&file).expect("file start should resolve to its dir");
800        assert_eq!(found, ws);
801    }
802
803    #[test]
804    fn find_workspace_root_deeper_marker_wins() {
805        // Outer and inner each carry `.memstead/workspace.toml`. The walk
806        // starts deep inside the inner dir and must resolve to the
807        // inner — deeper marker wins because the upward walk stops at
808        // the first match.
809        let tmp = TempDir::new().unwrap();
810        let outer = tmp.path().join("outer");
811        let inner = outer.join("inner");
812        let deep = inner.join("a").join("b");
813        std::fs::create_dir_all(&deep).unwrap();
814        touch_marker(&outer);
815        touch_marker(&inner);
816        let found = find_workspace_root(&deep).expect("walk should find the inner marker");
817        assert_eq!(found.canonicalize().unwrap(), inner.canonicalize().unwrap());
818    }
819}