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