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 /// Render rich, fully-inlined recovery prose for the agent-visible
248 /// text channel. Closes the asymmetry where structured `details.X`
249 /// fields stayed off the agent's text channel. Each lifecycle
250 /// variant with a structured list (`patterns`, `referring_mems`,
251 /// `allowed_schemas`) inlines the full payload; wrapped base-engine
252 /// errors delegate to [`EngineError::prose_render`]; trivial variants
253 /// fall back to `Display`.
254 pub fn prose_render(&self) -> String {
255 match self {
256 FullEngineError::Engine(inner) => inner.prose_render(),
257 FullEngineError::MemPathNotAllowed {
258 attempted,
259 candidate,
260 patterns,
261 reason,
262 policy_table,
263 } => {
264 let patterns_inline = if patterns.is_empty() {
265 "(no rules configured)".to_string()
266 } else {
267 patterns
268 .iter()
269 .map(|p| format!("'{p}'"))
270 .collect::<Vec<_>>()
271 .join(", ")
272 };
273 // Each reason gets the sentence that fits ITS
274 // situation, and the allowlist remedy is named only
275 // where adding a rule actually is the remedy —
276 // `outside_workspace` is not fixed by a rule, so it
277 // keeps the plain refusal.
278 let verb = if *policy_table == "mem_management.delete" {
279 "deletion"
280 } else {
281 "creation"
282 };
283 let allow_cmd = allowlist_remedy(policy_table);
284 match *reason {
285 "no_allowlist_configured" => format!(
286 "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.",
287 attempted.display()
288 ),
289 "no_match" => format!(
290 "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}`.",
291 attempted.display()
292 ),
293 _ => format!(
294 "mem path not allowed by `[[{policy_table}]]`: candidate '{candidate}' (resolved location '{}') did not match any allowlist rule (reason: {reason}). Configured patterns: {patterns_inline}.",
295 attempted.display()
296 ),
297 }
298 }
299 FullEngineError::MemSchemaNotAllowed {
300 candidate,
301 matched_pattern,
302 requested_schema,
303 allowed_schemas,
304 } => {
305 let allowed_inline = if allowed_schemas.is_empty() {
306 "(none)".to_string()
307 } else {
308 allowed_schemas.join(", ")
309 };
310 format!(
311 "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."
312 )
313 }
314 FullEngineError::MemReferencedByPolicy {
315 name,
316 referring_mems,
317 } => {
318 let inline = if referring_mems.is_empty() {
319 "(none)".to_string()
320 } else {
321 referring_mems.join(", ")
322 };
323 format!(
324 "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."
325 )
326 }
327 // InvalidMemName, ConfigAlreadyExists, MemStorageResidueDetected:
328 // `Display` already inlines every field; fall back.
329 _ => self.to_string(),
330 }
331 }
332
333 /// Variant-specific recovery payload, rendered as a structured
334 /// JSON object that surfaces under `error.details` in MCP / CLI
335 /// envelopes. The CLI's mem commands used to discard the engine's
336 /// structured details because the lift code didn't have a single
337 /// source of truth —
338 /// this mirrors `EngineError::details()` so the lift can call
339 /// `err.details()` directly without hand-maintaining each per-
340 /// variant payload at the CLI surface.
341 ///
342 /// `Engine(inner)` delegates to `EngineError::details()`. Lifecycle
343 /// variants return the same JSON object shape `full_engine_err_unified`
344 /// builds on the MCP wire — both surfaces share the payload here
345 /// so they cannot drift.
346 pub fn details(&self) -> serde_json::Value {
347 match self {
348 FullEngineError::Engine(inner) => inner.details(),
349 FullEngineError::MemPathNotAllowed {
350 attempted,
351 candidate,
352 patterns,
353 reason,
354 policy_table,
355 } => {
356 let mut d = serde_json::json!({
357 "attempted": attempted.display().to_string(),
358 "candidate": candidate,
359 "patterns": patterns,
360 "reason": reason,
361 "policy_table": policy_table,
362 });
363 // The remedy rides only where adding a rule IS the
364 // remedy: `outside_workspace` is not fixed by an
365 // allowlist rule, so it carries none.
366 if matches!(*reason, "no_allowlist_configured" | "no_match") {
367 let cli = allowlist_remedy(policy_table);
368 d["remedy"] = serde_json::json!({ "cli": cli });
369 }
370 d
371 }
372 FullEngineError::InvalidMemName { name, reason } => {
373 serde_json::json!({ "name": name, "reason": reason })
374 }
375 FullEngineError::MemReferencedByPolicy {
376 name,
377 referring_mems,
378 } => serde_json::json!({
379 "name": name,
380 "referring_mems": referring_mems,
381 }),
382 FullEngineError::MemSchemaNotAllowed {
383 candidate,
384 matched_pattern,
385 requested_schema,
386 allowed_schemas,
387 } => serde_json::json!({
388 "candidate": candidate,
389 "matched_pattern": matched_pattern,
390 "requested_schema": requested_schema,
391 "allowed_schemas": allowed_schemas,
392 }),
393 FullEngineError::ConfigAlreadyExists { path } => serde_json::json!({
394 "path": path.display().to_string(),
395 "reason": "config_already_exists",
396 }),
397 FullEngineError::MemStorageResidueDetected {
398 branch_ref,
399 config_blob,
400 entity_count,
401 } => serde_json::json!({
402 "branch_ref": branch_ref,
403 "config_blob": config_blob,
404 "entity_count": entity_count,
405 "recovery": ["reattach", "force_overwrite", "hard_cleanup_first"],
406 }),
407 FullEngineError::MemNameRefConflict {
408 name,
409 branch_ref,
410 conflicting_branches,
411 suggestion,
412 } => serde_json::json!({
413 "name": name,
414 "branch_ref": branch_ref,
415 "conflicting_branches": conflicting_branches,
416 "suggestion": suggestion,
417 }),
418 }
419 }
420
421 /// Stable, surface-independent error code token.
422 ///
423 /// Matches `crate::EngineError::code()` for every variant —
424 /// wrapped base-engine errors delegate to the base mapping, lifecycle
425 /// variants return the exact strings the base enum returned for
426 /// them today. This is load-bearing: the wire-shape pins in
427 /// `memstead-mcp/tests/wire_shape.rs` assert these exact code strings.
428 pub fn code(&self) -> &'static str {
429 match self {
430 FullEngineError::Engine(e) => e.code(),
431 FullEngineError::MemPathNotAllowed { .. } => "MEM_PATH_NOT_ALLOWED",
432 FullEngineError::InvalidMemName { .. } => "INVALID_MEM_NAME",
433 FullEngineError::MemReferencedByPolicy { .. } => "MEM_REFERENCED_BY_POLICY",
434 FullEngineError::MemSchemaNotAllowed { .. } => "MEM_SCHEMA_NOT_ALLOWED",
435 FullEngineError::ConfigAlreadyExists { .. } => "CONFIG_ERROR",
436 FullEngineError::MemStorageResidueDetected { .. } => "MEM_STORAGE_RESIDUE_DETECTED",
437 FullEngineError::MemNameRefConflict { .. } => "MEM_NAME_REF_CONFLICT",
438 }
439 }
440}
441
442#[cfg(test)]
443mod tests {
444 use super::*;
445
446 /// Code strings track the wire vocabulary the full MCP surface
447 /// publishes. `MEM_REFERENCED_BY_POLICY` was renamed from the
448 /// pre-04 `MEM_HAS_REFERENCES` so the typed code matches the
449 /// actual fire condition (a workspace `[cross_mem_links]` grant,
450 /// not a materialised graph edge); the other three lifecycle
451 /// codes are unchanged from when these variants lived on
452 /// `crate::EngineError`.
453 #[test]
454 fn lifecycle_codes_pin_wire_vocabulary() {
455 let e = FullEngineError::MemPathNotAllowed {
456 attempted: PathBuf::from("/x"),
457 candidate: "x".into(),
458 patterns: vec![],
459 reason: "no_match",
460 policy_table: "mem_management.create",
461 };
462 assert_eq!(e.code(), "MEM_PATH_NOT_ALLOWED");
463
464 let e = FullEngineError::MemReferencedByPolicy {
465 name: "x".into(),
466 referring_mems: vec![],
467 };
468 assert_eq!(e.code(), "MEM_REFERENCED_BY_POLICY");
469
470 let e = FullEngineError::MemSchemaNotAllowed {
471 candidate: "x".into(),
472 matched_pattern: "p".into(),
473 requested_schema: "s".into(),
474 allowed_schemas: vec![],
475 };
476 assert_eq!(e.code(), "MEM_SCHEMA_NOT_ALLOWED");
477
478 let e = FullEngineError::ConfigAlreadyExists {
479 path: PathBuf::from("/x"),
480 };
481 assert_eq!(e.code(), "CONFIG_ERROR");
482
483 let e = FullEngineError::MemNameRefConflict {
484 name: "library/sample/notes".into(),
485 branch_ref: "refs/heads/library/sample/notes".into(),
486 conflicting_branches: vec!["library/sample".into()],
487 suggestion: Some("library/sample-notes".into()),
488 };
489 assert_eq!(e.code(), "MEM_NAME_REF_CONFLICT");
490 let text = e.to_string();
491 assert!(text.contains("`library/sample`"), "{text}");
492 assert!(text.contains("`library/sample-notes`"), "{text}");
493 assert_eq!(e.details()["suggestion"], "library/sample-notes");
494 }
495
496 /// Wrapped base-engine errors delegate `code()` to the base mapping.
497 /// Any drift in the base enum's code strings rolls through this
498 /// path automatically — the full layer never re-stringifies.
499 #[test]
500 fn wrapped_base_engine_error_delegates_code() {
501 let e: FullEngineError = EngineError::UnknownMem("specs".into()).into();
502 assert_eq!(e.code(), "UNKNOWN_MEM");
503 }
504
505 /// The `policy_table` field disambiguates which allowlist refused
506 /// without forcing an agent to thread subcommand context through
507 /// error handling. The structured `details` payload and the
508 /// `prose_render` text both surface the table name.
509 #[test]
510 fn mem_path_not_allowed_carries_policy_table_in_details_and_prose() {
511 let create_err = FullEngineError::MemPathNotAllowed {
512 attempted: PathBuf::from("/ws/scratch-2"),
513 candidate: "scratch-2".into(),
514 patterns: vec!["specs".into()],
515 reason: "no_match",
516 policy_table: "mem_management.create",
517 };
518 let details = create_err.details();
519 assert_eq!(details["policy_table"], "mem_management.create");
520 assert_eq!(details["reason"], "no_match");
521 let prose = create_err.prose_render();
522 assert!(
523 prose.contains("mem_management.create"),
524 "prose must name the refusing allowlist: {prose}"
525 );
526
527 // Delete-path symmetric — policy_table flips to the delete table.
528 let delete_err = FullEngineError::MemPathNotAllowed {
529 attempted: PathBuf::from("/ws/archive-src"),
530 candidate: "archive-src".into(),
531 patterns: vec!["specs".into()],
532 reason: "no_match",
533 policy_table: "mem_management.delete",
534 };
535 assert_eq!(
536 delete_err.details()["policy_table"],
537 "mem_management.delete"
538 );
539 let prose = delete_err.prose_render();
540 assert!(
541 prose.contains("mem_management.delete"),
542 "prose must name the refusing allowlist: {prose}"
543 );
544 }
545
546 /// `no_allowlist_configured` names the concrete grant command —
547 /// pattern and schema pin included — in both the prose and the
548 /// structured `details.remedy`, so the first-time caller can
549 /// proceed from the refusal alone.
550 #[test]
551 fn no_allowlist_configured_names_the_grant_command() {
552 let err = FullEngineError::MemPathNotAllowed {
553 attempted: PathBuf::from("/ws/notes"),
554 candidate: "notes".into(),
555 patterns: vec![],
556 reason: "no_allowlist_configured",
557 policy_table: "mem_management.create",
558 };
559 let prose = err.prose_render();
560 assert!(
561 prose.contains("memstead workspace allow-create"),
562 "prose names the CLI remedy: {prose}"
563 );
564 assert!(
565 prose.contains("--schema"),
566 "prose names the schema pin: {prose}"
567 );
568 assert!(
569 prose.contains("operator surface"),
570 "prose names policy as an operator act: {prose}"
571 );
572 let details = err.details();
573 assert!(
574 details["remedy"]["cli"]
575 .as_str()
576 .unwrap()
577 .contains("allow-create"),
578 "details carry the remedy: {details}"
579 );
580 // Policy is not editable from MCP, so the remedy names no tool
581 // — a pointer at a removed tool is worse than no pointer.
582 assert!(
583 details["remedy"]["mcp"].is_null(),
584 "the remedy names no MCP tool: {details}"
585 );
586 assert!(
587 !prose.contains("memstead_workspace_"),
588 "prose names no removed MCP tool: {prose}"
589 );
590
591 // Delete-path variant names allow-delete, without a schema pin.
592 let err = FullEngineError::MemPathNotAllowed {
593 attempted: PathBuf::from("/ws/notes"),
594 candidate: "notes".into(),
595 patterns: vec![],
596 reason: "no_allowlist_configured",
597 policy_table: "mem_management.delete",
598 };
599 let prose = err.prose_render();
600 assert!(prose.contains("memstead workspace allow-delete"), "{prose}");
601 assert!(!prose.contains("--schema"), "{prose}");
602 assert!(
603 err.details()["remedy"]["cli"]
604 .as_str()
605 .unwrap()
606 .contains("allow-delete"),
607 "{:?}",
608 err.details()
609 );
610 }
611
612 /// `no_match` speaks to ITS situation — rules exist, none matched
613 /// — with a sentence distinct from the empty-allowlist one, while
614 /// still naming the covering-rule remedy.
615 #[test]
616 fn no_match_sentence_is_distinct_and_names_patterns() {
617 let no_match = FullEngineError::MemPathNotAllowed {
618 attempted: PathBuf::from("/ws/scratch"),
619 candidate: "scratch".into(),
620 patterns: vec!["specs".into(), "team/*".into()],
621 reason: "no_match",
622 policy_table: "mem_management.create",
623 };
624 let empty = FullEngineError::MemPathNotAllowed {
625 attempted: PathBuf::from("/ws/scratch"),
626 candidate: "scratch".into(),
627 patterns: vec![],
628 reason: "no_allowlist_configured",
629 policy_table: "mem_management.create",
630 };
631 let no_match_prose = no_match.prose_render();
632 let empty_prose = empty.prose_render();
633 assert_ne!(no_match_prose, empty_prose);
634 assert!(
635 no_match_prose.contains("'specs'") && no_match_prose.contains("'team/*'"),
636 "no_match names the configured patterns: {no_match_prose}"
637 );
638 assert!(
639 no_match_prose.contains("allow-create"),
640 "no_match still names the covering-rule remedy: {no_match_prose}"
641 );
642 assert!(no_match.details()["remedy"].is_object());
643 }
644
645 /// `outside_workspace` gains NO allowlist remedy — adding a rule
646 /// does not fix a workspace-external location, so suggesting one
647 /// would be wrong. Neither channel mentions the grant command.
648 #[test]
649 fn outside_workspace_carries_no_allowlist_remedy() {
650 let err = FullEngineError::MemPathNotAllowed {
651 attempted: PathBuf::from("/elsewhere/x"),
652 candidate: "../x".into(),
653 patterns: vec!["specs".into()],
654 reason: "outside_workspace",
655 policy_table: "mem_management.create",
656 };
657 let prose = err.prose_render();
658 assert!(!prose.contains("allow-create"), "{prose}");
659 assert!(!prose.contains("allow_create"), "{prose}");
660 let details = err.details();
661 assert!(details.get("remedy").is_none(), "{details}");
662 // The rest of the payload is unchanged.
663 assert_eq!(details["reason"], "outside_workspace");
664 }
665}