Skip to main content

memstead_base/
error.rs

1//! Lifecycle error envelope.
2//!
3//! Wrap-not-embed: [`FullEngineError`] **wraps** [`crate::EngineError`]
4//! via `From`, so lifecycle code paths propagate an engine failure
5//! without re-wrapping at each call site, and the MCP render layer
6//! reads the wrapped chain to produce the typed `code`.
7//!
8//! The four lifecycle-only variants live here rather than on
9//! `crate::EngineError`: they are produced by the mem-management
10//! orchestrator (`create_mem` / `delete_mem`), which returns
11//! `Result<_, FullEngineError>`. The name dates from the crate split
12//! this envelope outlived (`memstead-engine` folded into this crate);
13//! the type keeps it so consumers need no rename.
14
15use std::path::PathBuf;
16
17use crate::EngineError;
18
19/// Errors surfaced by the full engine extension.
20///
21/// `Engine(EngineError)` wraps any failure that originates in the
22/// underlying base engine (`memstead_base::Engine`): the lifecycle
23/// orchestrators that delegate to `crate::Engine` propagate base-engine
24/// errors verbatim through this variant (`#[from]`), so the wire-rendering
25/// layer at the MCP surface can recover the base engine's `code()` for any
26/// wrapped variant.
27///
28/// The remaining variants are **lifecycle-only**: they fire from the
29/// full mem management orchestrator (`create_mem` / `delete_mem`)
30/// and have no base-engine fire conditions. They live in this crate
31/// alongside their orchestrator.
32#[derive(Debug, thiserror::Error)]
33pub enum FullEngineError {
34    /// Wrapped base-engine error. Use this variant whenever a lifecycle
35    /// code path delegates to `crate::Engine` and a base-engine
36    /// failure should surface unchanged.
37    #[error(transparent)]
38    Engine(#[from] EngineError),
39
40    /// `create_mem` / `delete_mem` rejected because the mem
41    /// path is not covered by an allowlist rule. `reason` is one of
42    /// `no_allowlist_configured` / `no_match` / `outside_workspace`.
43    /// `policy_table` names the refusing allowlist —
44    /// `"mem_management.create"` or `"mem_management.delete"` —
45    /// so an agent recovering from the envelope knows which TOML
46    /// table to edit without threading subcommand context through
47    /// error handling. The two discriminators are orthogonal: `reason`
48    /// names *why* the gate refused; `policy_table` names *which*
49    /// gate refused.
50    #[error("mem path not allowed by [[{policy_table}]]: {candidate} ({reason})")]
51    MemPathNotAllowed {
52        attempted: PathBuf,
53        candidate: String,
54        patterns: Vec<String>,
55        reason: &'static str,
56        policy_table: &'static str,
57    },
58
59    /// `create_mem` rejected before the allowlist check because the
60    /// supplied `name` is structurally malformed — empty, whitespace,
61    /// invalid characters, or carries the reserved `__` prefix.
62    /// `reason` discriminates the four shapes so an agent who typed
63    /// the wrong thing gets a recoverable signal instead of an
64    /// allowlist refusal. Split out of the `MemPathNotAllowed
65    /// (no_match)` catch-all so the structural failure modes are
66    /// visible.
67    #[error("mem name `{name}` is invalid ({reason})")]
68    InvalidMemName { name: String, reason: &'static str },
69
70    /// `delete_mem` rejected because the workspace
71    /// `[cross_mem_links]` policy grants one or more other mems
72    /// permission to write into this one. `referring_mems` lists the
73    /// granting mems sorted alphabetically so the agent can walk
74    /// the policy table. The condition is a *policy grant*, not a
75    /// materialised graph edge — revoking the grant in
76    /// `.memstead/workspace.toml` is the recovery path.
77    #[error(
78        "mem {name} cannot be deleted: workspace `[cross_mem_links]` policy grants {referring_mems:?} write-into permission — revoke that grant and retry"
79    )]
80    MemReferencedByPolicy {
81        name: String,
82        referring_mems: Vec<String>,
83    },
84
85    /// `create_mem` rejected because the matched create-rule does
86    /// not allow the requested schema. `allowed_schemas` is the
87    /// canonicalised allow-list (each entry `name@version`).
88    #[error(
89        "schema {requested_schema} not allowed by create-rule {matched_pattern:?} for candidate {candidate:?}"
90    )]
91    MemSchemaNotAllowed {
92        candidate: String,
93        matched_pattern: String,
94        requested_schema: String,
95        allowed_schemas: Vec<String>,
96    },
97
98    /// `create_mem` rejected because the target `.memstead/config.json`
99    /// already exists at the requested location — the engine never
100    /// silently overwrites a prior attempt. The message names the
101    /// working remedy: an existing folder mem is adopted, not
102    /// recreated.
103    #[error(
104        "config already exists at {path} — an existing folder mem lives there; \
105         re-attach it instead of creating: pass recovery `reattach` \
106         (CLI: `memstead mem init <name> --storage folder --location <dir> --reattach`)"
107    )]
108    ConfigAlreadyExists { path: PathBuf },
109
110    /// `create_mem` detected on-disk storage residue for the
111    /// requested branch path that is not reflected in the in-memory
112    /// mem router — typically left over by a crash or a
113    /// partially-failed delete. The caller must select an
114    /// explicit recovery action via [`MemCreateParams::recovery`]
115    /// (`Reattach`, `ForceOverwrite`, or `HardCleanupFirst`) and
116    /// retry; the special case of `unregistered_at`-tombstoned
117    /// residue (deliberate operator state from `memstead mem
118    /// unregister`) defaults to `Reattach` without this refusal. The
119    /// payload carries the composed branch ref, the config-blob path,
120    /// and the entity count of the residual data so the caller can
121    /// decide between adopting and discarding.
122    #[error(
123        "mem storage residue detected at branch `{branch_ref}`: \
124         {entity_count} entities preserved from a prior session — \
125         re-run with `recovery: reattach` to adopt, `recovery: \
126         force_overwrite` to destroy, or `recovery: \
127         hard_cleanup_first` to refuse until `memstead mem delete` is run"
128    )]
129    MemStorageResidueDetected {
130        /// Composed branch reference (`refs/heads/<branch_leaf>`)
131        /// that carries the residue.
132        branch_ref: String,
133        /// Tree path of the `__MEMSTEAD:mems/<branch_leaf>/config.json`
134        /// blob (or `None` when the branch exists but the config blob
135        /// has already been pruned).
136        config_blob: Option<String>,
137        /// Best-effort entity count on the residual branch. Reads
138        /// the branch's tip tree and counts `.md` entries; `0` when
139        /// the count is unavailable.
140        entity_count: usize,
141    },
142
143    /// `create_mem` refused a git-branch name that git's ref namespace
144    /// cannot hold beside an existing mem branch: refs are files in
145    /// directories, so `refs/heads/library/sample` and
146    /// `refs/heads/library/sample/notes` cannot coexist, in either
147    /// order of creation. Refused before any write, so nothing lands on
148    /// `__MEMSTEAD`. `suggestion` names a sibling spelling where one
149    /// follows from the shape (the child case: the parent's leaf and the
150    /// rest joined by a hyphen).
151    #[error("{}", ref_conflict_message(.name, .branch_ref, .conflicting_branches, .suggestion))]
152    MemNameRefConflict {
153        /// The requested mem name.
154        name: String,
155        /// The branch the name would have become (`refs/heads/<name>`).
156        branch_ref: String,
157        /// The existing branches that sit above or below it in the ref
158        /// namespace, as branch names (without `refs/heads/`).
159        conflicting_branches: Vec<String>,
160        /// A sibling name that git can hold, where the shape yields one.
161        suggestion: Option<String>,
162    },
163}
164
165fn ref_conflict_message(
166    name: &str,
167    branch_ref: &str,
168    conflicting_branches: &[String],
169    suggestion: &Option<String>,
170) -> String {
171    let listed = conflicting_branches
172        .iter()
173        .map(|b| format!("`{b}`"))
174        .collect::<Vec<_>>()
175        .join(", ");
176    let hint = match suggestion {
177        Some(s) => format!(" Pick a sibling name instead, for example `{s}`."),
178        None => " Pick a name that is neither a parent nor a child path of an existing mem branch."
179            .to_string(),
180    };
181    format!(
182        "mem name '{name}' cannot become branch `{branch_ref}`: git keeps refs as files in \
183         directories, and the existing mem branch(es) {listed} would be a parent or child path \
184         of it.{hint}"
185    )
186}
187
188/// Recovery shape for `create_mem` against pre-existing storage
189/// residue. A single enum field with three variants structurally
190/// enforces mutual exclusion on the wire (a three-boolean shape would
191/// need a runtime-validation step instead).
192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
193pub enum RecoveryAction {
194    /// Adopt the residual entities and register the existing branch
195    /// as a fresh writable mount. The seed-commit step is skipped —
196    /// the prior session's history is preserved unchanged. Emits a
197    /// `MemReattachedAfterUnregister` warning when the residue
198    /// carries an `unregistered_at` tombstone (audit signal).
199    Reattach,
200    /// Destroy the residual branch + `__MEMSTEAD` config blob (and any
201    /// tombstone) in one ref-edit transaction, then proceed with
202    /// the normal create path. The prior entities are gone.
203    ForceOverwrite,
204    /// Refuse with a typed code instructing the caller to run
205    /// `memstead mem delete <name>` first. Hard barrier against
206    /// destructive auto-recovery even with an explicit recovery
207    /// flag — for operators who want the residue cleanup to be a
208    /// separate, named operation.
209    HardCleanupFirst,
210}
211
212impl RecoveryAction {
213    /// Wire-token rendering (`reattach` / `force_overwrite` /
214    /// `hard_cleanup_first`). Stable across the surface — used by
215    /// the MCP serde tag, the CLI flag bridge, and error-envelope
216    /// rendering.
217    pub fn as_wire_str(&self) -> &'static str {
218        match self {
219            RecoveryAction::Reattach => "reattach",
220            RecoveryAction::ForceOverwrite => "force_overwrite",
221            RecoveryAction::HardCleanupFirst => "hard_cleanup_first",
222        }
223    }
224}
225
226/// The concrete grant command for a refusing allowlist table — the
227/// single source both the prose and the structured `details.remedy`
228/// render, so the two channels cannot drift. The create form names the
229/// pattern and the schema pin because `allow-create` requires both;
230/// delete rules have no schema dimension.
231///
232/// Operator surfaces only, deliberately: workspace policy is the
233/// operator deciding what an agent may do, so it is not editable from
234/// the agent's own tool surface. The CLI form is what an agent reports
235/// and a person runs; the operator-authenticated web API carries the
236/// same operations. Naming an MCP tool here would point at one that no
237/// longer exists.
238fn allowlist_remedy(policy_table: &str) -> &'static str {
239    if policy_table == "mem_management.delete" {
240        "memstead workspace allow-delete '<pattern>'"
241    } else {
242        "memstead workspace allow-create '<pattern>' --schema <name@version>"
243    }
244}
245
246impl FullEngineError {
247    /// Refuse a name a folder mem cannot take: the structural refusals
248    /// every mem name meets, then the folder slug shape (lowercase letters,
249    /// digits and hyphens), as `invalid_char`.
250    pub fn check_folder_mem_name(name: &str) -> Result<(), FullEngineError> {
251        let refuse = |reason: &'static str| FullEngineError::InvalidMemName {
252            name: name.to_string(),
253            reason,
254        };
255        if let Some(reason) = crate::mem_management::lifecycle::classify_invalid_mem_name(name) {
256            return Err(refuse(reason));
257        }
258        if crate::filesystem::config::validate_mem_name(name).is_err() {
259            return Err(refuse("invalid_char"));
260        }
261        Ok(())
262    }
263}
264
265impl FullEngineError {
266    /// Render rich, fully-inlined recovery prose for the agent-visible
267    /// text channel. Closes the asymmetry where structured `details.X`
268    /// fields stayed off the agent's text channel. Each lifecycle
269    /// variant with a structured list (`patterns`, `referring_mems`,
270    /// `allowed_schemas`) inlines the full payload; wrapped base-engine
271    /// errors delegate to [`EngineError::prose_render`]; trivial variants
272    /// fall back to `Display`.
273    pub fn prose_render(&self) -> String {
274        match self {
275            FullEngineError::Engine(inner) => inner.prose_render(),
276            FullEngineError::MemPathNotAllowed {
277                attempted,
278                candidate,
279                patterns,
280                reason,
281                policy_table,
282            } => {
283                let patterns_inline = if patterns.is_empty() {
284                    "(no rules configured)".to_string()
285                } else {
286                    patterns
287                        .iter()
288                        .map(|p| format!("'{p}'"))
289                        .collect::<Vec<_>>()
290                        .join(", ")
291                };
292                // Each reason gets the sentence that fits ITS
293                // situation, and the allowlist remedy is named only
294                // where adding a rule actually is the remedy —
295                // `outside_workspace` is not fixed by a rule, so it
296                // keeps the plain refusal.
297                let verb = if *policy_table == "mem_management.delete" {
298                    "deletion"
299                } else {
300                    "creation"
301                };
302                let allow_cmd = allowlist_remedy(policy_table);
303                match *reason {
304                    "no_allowlist_configured" => format!(
305                        "mem {verb} is refused by default: this workspace has no `[[{policy_table}]]` allowlist rules (candidate '{candidate}', resolved location '{}'). Grant the permission first — `{allow_cmd}`, e.g. with pattern '{candidate}' — then retry. Workspace policy is an operator surface: report the command, a person runs it.",
306                        attempted.display()
307                    ),
308                    "no_match" => format!(
309                        "mem path not allowed by `[[{policy_table}]]`: candidate '{candidate}' (resolved location '{}') matched none of the configured patterns: {patterns_inline}. Use a name matching an existing pattern, or ask the operator to add a covering rule — `{allow_cmd}`.",
310                        attempted.display()
311                    ),
312                    _ => format!(
313                        "mem path not allowed by `[[{policy_table}]]`: candidate '{candidate}' (resolved location '{}') did not match any allowlist rule (reason: {reason}). Configured patterns: {patterns_inline}.",
314                        attempted.display()
315                    ),
316                }
317            }
318            FullEngineError::MemSchemaNotAllowed {
319                candidate,
320                matched_pattern,
321                requested_schema,
322                allowed_schemas,
323            } => {
324                let allowed_inline = if allowed_schemas.is_empty() {
325                    "(none)".to_string()
326                } else {
327                    allowed_schemas.join(", ")
328                };
329                format!(
330                    "schema '{requested_schema}' not allowed by create-rule '{matched_pattern}' for candidate '{candidate}' — allowed schemas: {allowed_inline}. Pick a schema from this list or add a new `[[mem_management.create]]` rule covering this candidate."
331                )
332            }
333            FullEngineError::MemReferencedByPolicy {
334                name,
335                referring_mems,
336            } => {
337                let inline = if referring_mems.is_empty() {
338                    "(none)".to_string()
339                } else {
340                    referring_mems.join(", ")
341                };
342                format!(
343                    "mem {name} cannot be deleted: workspace `[cross_mem_links]` policy grants the following mems write-into permission: {inline}. Ask the operator to revoke each grant (`memstead workspace revoke-cross-link <from> <to>`) and retry."
344                )
345            }
346            // InvalidMemName, ConfigAlreadyExists, MemStorageResidueDetected:
347            // `Display` already inlines every field; fall back.
348            _ => self.to_string(),
349        }
350    }
351
352    /// Variant-specific recovery payload, rendered as a structured
353    /// JSON object that surfaces under `error.details` in MCP / CLI
354    /// envelopes. The CLI's mem commands used to discard the engine's
355    /// structured details because the lift code didn't have a single
356    /// source of truth —
357    /// this mirrors `EngineError::details()` so the lift can call
358    /// `err.details()` directly without hand-maintaining each per-
359    /// variant payload at the CLI surface.
360    ///
361    /// `Engine(inner)` delegates to `EngineError::details()`. Lifecycle
362    /// variants return the same JSON object shape `full_engine_err_unified`
363    /// builds on the MCP wire — both surfaces share the payload here
364    /// so they cannot drift.
365    pub fn details(&self) -> serde_json::Value {
366        match self {
367            FullEngineError::Engine(inner) => inner.details(),
368            FullEngineError::MemPathNotAllowed {
369                attempted,
370                candidate,
371                patterns,
372                reason,
373                policy_table,
374            } => {
375                let mut d = serde_json::json!({
376                    "attempted": attempted.display().to_string(),
377                    "candidate": candidate,
378                    "patterns": patterns,
379                    "reason": reason,
380                    "policy_table": policy_table,
381                });
382                // The remedy rides only where adding a rule IS the
383                // remedy: `outside_workspace` is not fixed by an
384                // allowlist rule, so it carries none.
385                if matches!(*reason, "no_allowlist_configured" | "no_match") {
386                    let cli = allowlist_remedy(policy_table);
387                    d["remedy"] = serde_json::json!({ "cli": cli });
388                }
389                d
390            }
391            FullEngineError::InvalidMemName { name, reason } => {
392                serde_json::json!({ "name": name, "reason": reason })
393            }
394            FullEngineError::MemReferencedByPolicy {
395                name,
396                referring_mems,
397            } => serde_json::json!({
398                "name": name,
399                "referring_mems": referring_mems,
400            }),
401            FullEngineError::MemSchemaNotAllowed {
402                candidate,
403                matched_pattern,
404                requested_schema,
405                allowed_schemas,
406            } => serde_json::json!({
407                "candidate": candidate,
408                "matched_pattern": matched_pattern,
409                "requested_schema": requested_schema,
410                "allowed_schemas": allowed_schemas,
411            }),
412            FullEngineError::ConfigAlreadyExists { path } => serde_json::json!({
413                "path": path.display().to_string(),
414                "reason": "config_already_exists",
415            }),
416            FullEngineError::MemStorageResidueDetected {
417                branch_ref,
418                config_blob,
419                entity_count,
420            } => serde_json::json!({
421                "branch_ref": branch_ref,
422                "config_blob": config_blob,
423                "entity_count": entity_count,
424                "recovery": ["reattach", "force_overwrite", "hard_cleanup_first"],
425            }),
426            FullEngineError::MemNameRefConflict {
427                name,
428                branch_ref,
429                conflicting_branches,
430                suggestion,
431            } => serde_json::json!({
432                "name": name,
433                "branch_ref": branch_ref,
434                "conflicting_branches": conflicting_branches,
435                "suggestion": suggestion,
436            }),
437        }
438    }
439
440    /// Stable, surface-independent error code token.
441    ///
442    /// Matches `crate::EngineError::code()` for every variant —
443    /// wrapped base-engine errors delegate to the base mapping, lifecycle
444    /// variants return the exact strings the base enum returned for
445    /// them today. This is load-bearing: the wire-shape pins in
446    /// `memstead-mcp/tests/wire_shape.rs` assert these exact code strings.
447    pub fn code(&self) -> &'static str {
448        match self {
449            FullEngineError::Engine(e) => e.code(),
450            FullEngineError::MemPathNotAllowed { .. } => "MEM_PATH_NOT_ALLOWED",
451            FullEngineError::InvalidMemName { .. } => "INVALID_MEM_NAME",
452            FullEngineError::MemReferencedByPolicy { .. } => "MEM_REFERENCED_BY_POLICY",
453            FullEngineError::MemSchemaNotAllowed { .. } => "MEM_SCHEMA_NOT_ALLOWED",
454            FullEngineError::ConfigAlreadyExists { .. } => "CONFIG_ERROR",
455            FullEngineError::MemStorageResidueDetected { .. } => "MEM_STORAGE_RESIDUE_DETECTED",
456            FullEngineError::MemNameRefConflict { .. } => "MEM_NAME_REF_CONFLICT",
457        }
458    }
459}
460
461#[cfg(test)]
462mod tests {
463    use super::*;
464
465    /// Code strings track the wire vocabulary the full MCP surface
466    /// publishes. `MEM_REFERENCED_BY_POLICY` was renamed from the
467    /// pre-04 `MEM_HAS_REFERENCES` so the typed code matches the
468    /// actual fire condition (a workspace `[cross_mem_links]` grant,
469    /// not a materialised graph edge); the other three lifecycle
470    /// codes are unchanged from when these variants lived on
471    /// `crate::EngineError`.
472    #[test]
473    fn lifecycle_codes_pin_wire_vocabulary() {
474        let e = FullEngineError::MemPathNotAllowed {
475            attempted: PathBuf::from("/x"),
476            candidate: "x".into(),
477            patterns: vec![],
478            reason: "no_match",
479            policy_table: "mem_management.create",
480        };
481        assert_eq!(e.code(), "MEM_PATH_NOT_ALLOWED");
482
483        let e = FullEngineError::MemReferencedByPolicy {
484            name: "x".into(),
485            referring_mems: vec![],
486        };
487        assert_eq!(e.code(), "MEM_REFERENCED_BY_POLICY");
488
489        let e = FullEngineError::MemSchemaNotAllowed {
490            candidate: "x".into(),
491            matched_pattern: "p".into(),
492            requested_schema: "s".into(),
493            allowed_schemas: vec![],
494        };
495        assert_eq!(e.code(), "MEM_SCHEMA_NOT_ALLOWED");
496
497        let e = FullEngineError::ConfigAlreadyExists {
498            path: PathBuf::from("/x"),
499        };
500        assert_eq!(e.code(), "CONFIG_ERROR");
501
502        let e = FullEngineError::MemNameRefConflict {
503            name: "library/sample/notes".into(),
504            branch_ref: "refs/heads/library/sample/notes".into(),
505            conflicting_branches: vec!["library/sample".into()],
506            suggestion: Some("library/sample-notes".into()),
507        };
508        assert_eq!(e.code(), "MEM_NAME_REF_CONFLICT");
509        let text = e.to_string();
510        assert!(text.contains("`library/sample`"), "{text}");
511        assert!(text.contains("`library/sample-notes`"), "{text}");
512        assert_eq!(e.details()["suggestion"], "library/sample-notes");
513    }
514
515    /// Wrapped base-engine errors delegate `code()` to the base mapping.
516    /// Any drift in the base enum's code strings rolls through this
517    /// path automatically — the full layer never re-stringifies.
518    #[test]
519    fn wrapped_base_engine_error_delegates_code() {
520        let e: FullEngineError = EngineError::UnknownMem {
521            name: "specs".into(),
522            known_mems: Vec::new(),
523            writable_mems: Vec::new(),
524        }
525        .into();
526        assert_eq!(e.code(), "UNKNOWN_MEM");
527    }
528
529    /// The `policy_table` field disambiguates which allowlist refused
530    /// without forcing an agent to thread subcommand context through
531    /// error handling. The structured `details` payload and the
532    /// `prose_render` text both surface the table name.
533    #[test]
534    fn mem_path_not_allowed_carries_policy_table_in_details_and_prose() {
535        let create_err = FullEngineError::MemPathNotAllowed {
536            attempted: PathBuf::from("/ws/scratch-2"),
537            candidate: "scratch-2".into(),
538            patterns: vec!["specs".into()],
539            reason: "no_match",
540            policy_table: "mem_management.create",
541        };
542        let details = create_err.details();
543        assert_eq!(details["policy_table"], "mem_management.create");
544        assert_eq!(details["reason"], "no_match");
545        let prose = create_err.prose_render();
546        assert!(
547            prose.contains("mem_management.create"),
548            "prose must name the refusing allowlist: {prose}"
549        );
550
551        // Delete-path symmetric — policy_table flips to the delete table.
552        let delete_err = FullEngineError::MemPathNotAllowed {
553            attempted: PathBuf::from("/ws/archive-src"),
554            candidate: "archive-src".into(),
555            patterns: vec!["specs".into()],
556            reason: "no_match",
557            policy_table: "mem_management.delete",
558        };
559        assert_eq!(
560            delete_err.details()["policy_table"],
561            "mem_management.delete"
562        );
563        let prose = delete_err.prose_render();
564        assert!(
565            prose.contains("mem_management.delete"),
566            "prose must name the refusing allowlist: {prose}"
567        );
568    }
569
570    /// `no_allowlist_configured` names the concrete grant command —
571    /// pattern and schema pin included — in both the prose and the
572    /// structured `details.remedy`, so the first-time caller can
573    /// proceed from the refusal alone.
574    #[test]
575    fn no_allowlist_configured_names_the_grant_command() {
576        let err = FullEngineError::MemPathNotAllowed {
577            attempted: PathBuf::from("/ws/notes"),
578            candidate: "notes".into(),
579            patterns: vec![],
580            reason: "no_allowlist_configured",
581            policy_table: "mem_management.create",
582        };
583        let prose = err.prose_render();
584        assert!(
585            prose.contains("memstead workspace allow-create"),
586            "prose names the CLI remedy: {prose}"
587        );
588        assert!(
589            prose.contains("--schema"),
590            "prose names the schema pin: {prose}"
591        );
592        assert!(
593            prose.contains("operator surface"),
594            "prose names policy as an operator act: {prose}"
595        );
596        let details = err.details();
597        assert!(
598            details["remedy"]["cli"]
599                .as_str()
600                .unwrap()
601                .contains("allow-create"),
602            "details carry the remedy: {details}"
603        );
604        // Policy is not editable from MCP, so the remedy names no tool
605        // — a pointer at a removed tool is worse than no pointer.
606        assert!(
607            details["remedy"]["mcp"].is_null(),
608            "the remedy names no MCP tool: {details}"
609        );
610        assert!(
611            !prose.contains("memstead_workspace_"),
612            "prose names no removed MCP tool: {prose}"
613        );
614
615        // Delete-path variant names allow-delete, without a schema pin.
616        let err = FullEngineError::MemPathNotAllowed {
617            attempted: PathBuf::from("/ws/notes"),
618            candidate: "notes".into(),
619            patterns: vec![],
620            reason: "no_allowlist_configured",
621            policy_table: "mem_management.delete",
622        };
623        let prose = err.prose_render();
624        assert!(prose.contains("memstead workspace allow-delete"), "{prose}");
625        assert!(!prose.contains("--schema"), "{prose}");
626        assert!(
627            err.details()["remedy"]["cli"]
628                .as_str()
629                .unwrap()
630                .contains("allow-delete"),
631            "{:?}",
632            err.details()
633        );
634    }
635
636    /// `no_match` speaks to ITS situation — rules exist, none matched
637    /// — with a sentence distinct from the empty-allowlist one, while
638    /// still naming the covering-rule remedy.
639    #[test]
640    fn no_match_sentence_is_distinct_and_names_patterns() {
641        let no_match = FullEngineError::MemPathNotAllowed {
642            attempted: PathBuf::from("/ws/scratch"),
643            candidate: "scratch".into(),
644            patterns: vec!["specs".into(), "team/*".into()],
645            reason: "no_match",
646            policy_table: "mem_management.create",
647        };
648        let empty = FullEngineError::MemPathNotAllowed {
649            attempted: PathBuf::from("/ws/scratch"),
650            candidate: "scratch".into(),
651            patterns: vec![],
652            reason: "no_allowlist_configured",
653            policy_table: "mem_management.create",
654        };
655        let no_match_prose = no_match.prose_render();
656        let empty_prose = empty.prose_render();
657        assert_ne!(no_match_prose, empty_prose);
658        assert!(
659            no_match_prose.contains("'specs'") && no_match_prose.contains("'team/*'"),
660            "no_match names the configured patterns: {no_match_prose}"
661        );
662        assert!(
663            no_match_prose.contains("allow-create"),
664            "no_match still names the covering-rule remedy: {no_match_prose}"
665        );
666        assert!(no_match.details()["remedy"].is_object());
667    }
668
669    /// `outside_workspace` gains NO allowlist remedy — adding a rule
670    /// does not fix a workspace-external location, so suggesting one
671    /// would be wrong. Neither channel mentions the grant command.
672    #[test]
673    fn outside_workspace_carries_no_allowlist_remedy() {
674        let err = FullEngineError::MemPathNotAllowed {
675            attempted: PathBuf::from("/elsewhere/x"),
676            candidate: "../x".into(),
677            patterns: vec!["specs".into()],
678            reason: "outside_workspace",
679            policy_table: "mem_management.create",
680        };
681        let prose = err.prose_render();
682        assert!(!prose.contains("allow-create"), "{prose}");
683        assert!(!prose.contains("allow_create"), "{prose}");
684        let details = err.details();
685        assert!(details.get("remedy").is_none(), "{details}");
686        // The rest of the payload is unchanged.
687        assert_eq!(details["reason"], "outside_workspace");
688    }
689}