memstead-cli 0.3.0

Command-line interface for Memstead — query and mutate typed entity graphs from the shell. Default build produces the full `memstead` binary (multi-mem, git-backed); `--no-default-features` builds the lean folder-only surface.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
//! Memstead CLI library — the command modules, utility modules, and
//! the shared `CliError` behind the `memstead` binary (`src/main.rs`).
//!
//! One crate, two build configs. The default build (`mem-repo`
//! feature on) is the full `memstead`: every subcommand, including the
//! multi-mem / mem-repo lifecycle (mem, workspace, install,
//! batch-update, recover). `--no-default-features` drops the git-branch
//! backend and the mem-repo-only subcommands, yielding the lean
//! engine-agnostic surface (a CI / wasm-adjacent config, not shipped).

pub mod auth;
pub mod cli;
pub mod commands;
#[cfg(feature = "mem-repo")]
pub mod outer_gitignore;
pub mod output;
pub mod registry;
pub mod setup;

use output::ExitKind;

/// Stable wire token for genuinely-systemic failures the agent can't
/// recover from (I/O panic, store corruption, unreachable branch).
/// The `code` field is non-optional, so this constant exists for
/// callsites that explicitly choose it — defaulting to it is not
/// possible. Adding a new callsite using this constant should carry a
/// comment explaining why no recoverable typed code applies.
pub const INTERNAL_CODE: &str = "INTERNAL";

/// Argument-validation refusal: mutating commands require one of
/// `--auto-hash`, `--expected-hash`, or `--force`. The typed code lets
/// agents branch on the wire token rather than parsing the message.
pub const HASH_FLAG_REQUIRED_CODE: &str = "HASH_FLAG_REQUIRED";

/// `memstead init <target>` refusal: target directory is non-empty (the
/// init refuses to scribble over existing files / pre-existing
/// workspaces).
pub const TARGET_NOT_EMPTY_CODE: &str = "TARGET_NOT_EMPTY";

/// `memstead overview --chunk <N>` refusal: requested chunk index is
/// beyond the actual chunk count.
pub const CHUNK_OUT_OF_RANGE_CODE: &str = "CHUNK_OUT_OF_RANGE";

/// `memstead init` refusal: ancestor walk found an existing
/// `.memstead/workspace.toml` above the target. Without this guard a
/// standalone init would silently nest a fresh filesystem-mem
/// workspace inside an existing one, with neither workspace aware of
/// the other.
pub const WORKSPACE_ALREADY_EXISTS_ABOVE_CODE: &str = "WORKSPACE_ALREADY_EXISTS_ABOVE";

/// `memstead install <archive>` refusal: archive failed strict
/// validation (any of the variants the strict-archive validator can
/// produce).
pub const ARCHIVE_VALIDATION_FAILED_CODE: &str = "ARCHIVE_VALIDATION_FAILED";

/// Typed CLI error that carries an exit-code kind, a stable
/// `UPPER_SNAKE_CASE` code (matching `EngineError::code()` for
/// engine-sourced errors), and an optional structured details payload.
/// Wrap with `anyhow::Error` via `.into()` or `map_err` to propagate up
/// to `main`, which renders the error through
/// [`output::print_cli_error`] in the documented `{code, message, details}`
/// shape (or `memstead: ERROR [<CODE>]: <message>` on the text channel).
///
/// `code` is non-optional, so every construction site spells the wire
/// token — there is no `Option`-default-to-`INTERNAL` fallback that
/// could leak `INTERNAL` when a callsite forgets to set it.
/// Engine-sourced errors capture `EngineError::code()` via
/// [`CliError::from_engine_op`]; setup-layer paths pin their own typed
/// token at construction time.
///
/// `details` is the structured recovery payload — e.g. `HashMismatch`
/// populates `{"current": "<hash>"}` so scripts can lift the recovery
/// hash without re-reading the entity. The renderer surfaces it under
/// the `details` key of the JSON envelope.
#[derive(Debug)]
pub struct CliError {
    pub kind: ExitKind,
    pub code: &'static str,
    pub message: String,
    pub details: Option<serde_json::Value>,
}

impl std::fmt::Display for CliError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message)
    }
}

impl std::error::Error for CliError {}

impl CliError {
    /// Construct a typed CLI error with an exit-kind, wire code, and
    /// human message. Every callsite spells the code at construction
    /// time — there is no Option-default-to-INTERNAL fallback. Use
    /// [`INTERNAL_CODE`] explicitly for genuinely-systemic paths.
    pub fn new(kind: ExitKind, code: &'static str, message: impl Into<String>) -> Self {
        Self {
            kind,
            code,
            message: message.into(),
            details: None,
        }
    }

    pub fn with_details(mut self, details: serde_json::Value) -> Self {
        self.details = Some(details);
        self
    }

    /// Override the wire code on an existing `CliError`. This helper exists
    /// for callsites that build an error in steps (e.g.
    /// `setup` layers that mint the error before knowing whether to
    /// retag it with a more specific code). New code should spell the
    /// final code at [`CliError::new`] construction time.
    pub fn with_code(mut self, code: &'static str) -> Self {
        self.code = code;
        self
    }

    /// Field accessor preserved as a method for backward compatibility
    /// with the previous `Option<&'static str>` API. Now a trivial
    /// `self.code` return; kept so existing call sites don't need to
    /// flip method-call syntax to field-access syntax.
    pub fn effective_code(&self) -> &'static str {
        self.code
    }

    /// Map an [`memstead_base::EngineError`] to a typed CLI error with the
    /// right exit code (`NOT_FOUND` → 3, `HASH_MISMATCH` → 4,
    /// validation errors → 5, everything else → 1) and the typed wire
    /// code from `EngineError::code()`. Recovery payloads
    /// (`HashMismatch.current`, `HasIncomingRefs.referrers`,
    /// `WikiLinkWithoutRelation.missing`, etc.) land under `details` so
    /// `--json` callers consume the same `{code, message, details}`
    /// envelope they get over MCP — bit-identical wire shape across
    /// surfaces is the agent contract this method delivers.
    pub fn from_engine_op(e: memstead_base::EngineError) -> Self {
        use memstead_base::EngineError::*;
        let code = e.code();
        let (kind, details) = match &e {
            NotFound { id } => (ExitKind::NotFound, Some(serde_json::json!({ "id": id }))),
            HashMismatch {
                id,
                current,
                is_stub,
            } => (
                ExitKind::HashMismatch,
                Some(serde_json::json!({
                    "id": id,
                    "current": current,
                    "is_stub": is_stub,
                })),
            ),
            HasIncomingRefs { id, referrers } => {
                let referrers_json: Vec<_> = referrers
                    .iter()
                    .map(|r| {
                        serde_json::json!({
                            "from_id": r.from_id,
                            "rel_types": r.rel_types,
                            "mem": r.mem,
                            "capability": "write",
                        })
                    })
                    .collect();
                (
                    ExitKind::Validation,
                    Some(serde_json::json!({
                        "id": id,
                        "referrers": referrers_json,
                    })),
                )
            }
            MemHasIncomingRefs { mem, referrers } => {
                let referrers_json: Vec<_> = referrers
                    .iter()
                    .map(|r| {
                        serde_json::json!({
                            "from_id": r.from_id,
                            "rel_types": r.rel_types,
                            "mem": r.mem,
                        })
                    })
                    .collect();
                (
                    ExitKind::Validation,
                    Some(serde_json::json!({
                        "mem": mem,
                        "referrers": referrers_json,
                    })),
                )
            }
            WikiLinkWithoutRelation { from_id, missing } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "from_id": from_id,
                    "missing": missing,
                })),
            ),
            RelationHasBodyLinks {
                from_id,
                to_id,
                rel_type,
                body_links,
            } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "from_id": from_id,
                    "to_id": to_id,
                    "rel_type": rel_type,
                    "body_links": body_links,
                })),
            ),
            InvalidEntityId { id, reason } => (
                ExitKind::Validation,
                Some(serde_json::json!({ "id": id, "reason": reason })),
            ),
            InvalidWikiLinkTarget {
                raw,
                suggested,
                section,
                link_source,
                reason,
            } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "raw": raw,
                    "suggested": suggested,
                    "section": section,
                    "source": link_source,
                    "reason": reason,
                })),
            ),
            InvalidWikiLinkMem {
                raw,
                section,
                reason,
            } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "raw": raw,
                    "section": section,
                    "reason": reason,
                })),
            ),
            CrossMemLinkNotAllowed { from_mem, to_mem } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "from_mem": from_mem,
                    "to_mem": to_mem,
                })),
            ),
            CrossMemTargetNotFound {
                target_id,
                target_mem,
            } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "target_id": target_id,
                    "target_mem": target_mem,
                })),
            ),
            RenameNoOp { id, new_title } => (
                ExitKind::Validation,
                Some(serde_json::json!({ "id": id, "new_title": new_title })),
            ),
            StubCannotRelate { id } | StubNotUpdatable { id } | StubNotRenamable { id } => {
                (ExitKind::Validation, Some(serde_json::json!({ "id": id })))
            }
            AlreadyExists { id } => (ExitKind::Validation, Some(serde_json::json!({ "id": id }))),
            UnknownType {
                name,
                schema_ref,
                declared,
                suggestion,
            } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "name": name,
                    "schema_ref": schema_ref,
                    "declared": declared,
                    "suggestion": suggestion,
                })),
            ),
            Validation(v) => (ExitKind::Validation, Some(v.details())),
            MemConfigIncomplete {
                mem,
                missing_fields,
            } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "mem": mem,
                    "missing_fields": missing_fields,
                    "set_via": format!("memstead mem set-version {mem} <version>"),
                })),
            ),
            InvalidTitle(slug_err) => {
                use memstead_base::SlugError;
                let reason = slug_err.reason();
                let details = match slug_err {
                    SlugError::IdTooLong { input, length, max } => serde_json::json!({
                        "reason": reason,
                        "input": input,
                        "length": length,
                        "max": max,
                    }),
                    SlugError::TitleEmpty { input } => serde_json::json!({
                        "reason": reason,
                        "input": input,
                    }),
                    SlugError::TitleHasInvalidChars {
                        input,
                        invalid_chars,
                        proposed_slug,
                    } => {
                        let invalid_chars_str: Vec<String> =
                            invalid_chars.iter().map(|c| c.to_string()).collect();
                        serde_json::json!({
                            "reason": reason,
                            "input": input,
                            "invalid_chars": invalid_chars_str,
                            "proposed_slug": proposed_slug,
                        })
                    }
                    SlugError::TitleHasControlChars {
                        input,
                        control_chars,
                        proposed_slug,
                    } => {
                        let control_chars_str: Vec<String> = control_chars
                            .iter()
                            .map(|c| c.escape_default().to_string())
                            .collect();
                        serde_json::json!({
                            "reason": reason,
                            "input": input,
                            "control_chars": control_chars_str,
                            "proposed_slug": proposed_slug,
                        })
                    }
                };
                (ExitKind::Validation, Some(details))
            }
            // Exhaustiveness: the
            // arms below replace a pre-existing `_ => (Generic, None)`
            // wildcard that silently swallowed `DescriptionNotPermitted`,
            // `MissingRequiredDescription`, and the rename-policy /
            // partial-failure variants — trained CLI agents to treat
            // these as Generic (exit 1) without structured details. The
            // exhaustive match forces every new `EngineError` variant to
            // declare its CLI shape before it can land. Compiler is the
            // forcing function.
            DescriptionNotPermitted {
                rel_type,
                from_id,
                to_id,
            } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "rel_type": rel_type,
                    "from_id": from_id,
                    "to_id": to_id,
                })),
            ),
            MissingRequiredDescription {
                rel_type,
                from_id,
                to_id,
            } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "rel_type": rel_type,
                    "from_id": from_id,
                    "to_id": to_id,
                })),
            ),
            RelationManualAuthoringForbidden {
                rel_type,
                from_id,
                to_id,
                guidance,
            } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "rel_type": rel_type,
                    "from_id": from_id,
                    "to_id": to_id,
                    "guidance": guidance,
                })),
            ),
            CrossMemEdgeNotDeclared {
                source_schema,
                target_schema,
                rel_type,
                from_id,
                to_id,
            } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "source_schema": source_schema,
                    "target_schema": target_schema,
                    "rel_type": rel_type,
                    "from_id": from_id,
                    "to_id": to_id,
                })),
            ),
            RepairNotNeeded { id, recovery } => (
                ExitKind::Validation,
                Some(serde_json::json!({ "id": id, "recovery": recovery })),
            ),
            ConflictingSectionModes { section, modes } => (
                ExitKind::Validation,
                Some(serde_json::json!({ "section": section, "modes": modes })),
            ),
            RelationshipCycle {
                rel_type,
                from,
                to,
                existing_path,
                path_truncated,
            } => {
                let existing_path_json: Vec<String> =
                    existing_path.iter().map(|id| id.to_string()).collect();
                (
                    ExitKind::Validation,
                    Some(serde_json::json!({
                        "rel_type": rel_type,
                        "from": from.to_string(),
                        "to": to.to_string(),
                        "existing_path": existing_path_json,
                        "path_truncated": path_truncated,
                    })),
                )
            }
            SetAndUnsetConflict { keys } => (
                ExitKind::Validation,
                Some(serde_json::json!({ "keys": keys })),
            ),
            RequiredFieldUnset {
                field,
                entity_type,
                field_description,
                enum_values,
                type_write_rules,
                // `on_create` is a prose-dispatch discriminator only;
                // the structured details payload is identical on both
                // call sites.
                on_create: _,
                missing,
            } => {
                // `details.missing[]` carries every required-no-
                // default field unset on the create path. Each
                // entry echoes the type-level `write_rules`.
                let missing_json: Vec<_> = missing
                    .iter()
                    .map(|m| {
                        serde_json::json!({
                            "field": m.key,
                            "description": m.description,
                            "enum_values": m.enum_values,
                            "write_rules": type_write_rules,
                        })
                    })
                    .collect();
                (
                    ExitKind::Validation,
                    Some(serde_json::json!({
                        "field": field,
                        "entity_type": entity_type,
                        "field_description": field_description,
                        "enum_values": enum_values,
                        "type_write_rules": type_write_rules,
                        "missing": missing_json,
                    })),
                )
            }
            MissingRequiredSection {
                entity_type,
                missing_count,
                sections,
                type_guidance,
            } => {
                let sections_json: Vec<_> = sections
                    .iter()
                    .map(|s| {
                        serde_json::json!({
                            "entity_type": s.entity_type,
                            "key": s.key,
                            "heading": s.heading,
                            "write_rules": s.write_rules,
                        })
                    })
                    .collect();
                (
                    ExitKind::Validation,
                    Some(serde_json::json!({
                        "entity_type": entity_type,
                        "missing_count": missing_count,
                        "sections": sections_json,
                        "type_guidance": type_guidance,
                    })),
                )
            }
            PatchSectionEmpty { section } => (
                ExitKind::Validation,
                Some(serde_json::json!({ "section": section })),
            ),
            PatchOldNotFound {
                section,
                current_content,
                truncated,
            } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "section": section,
                    "current_content": current_content,
                    "truncated": truncated,
                })),
            ),
            RenameBlockedByCrossMemPolicy {
                from_mem,
                blocked_referrers,
            } => {
                let entries: Vec<_> = blocked_referrers
                    .iter()
                    .map(|r| {
                        serde_json::json!({
                            "from_mem": r.from_mem,
                            "to_mem": r.to_mem,
                            "count": r.count,
                        })
                    })
                    .collect();
                (
                    ExitKind::Validation,
                    Some(serde_json::json!({
                        "from_mem": from_mem,
                        "blocked_referrers": entries,
                    })),
                )
            }
            RenamePartialFailure {
                committed_mems,
                failed_mem,
                failure_cause,
            } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "committed_mems": committed_mems,
                    "failed_mem": failed_mem,
                    "failure_cause": failure_cause,
                })),
            ),
            UnknownMem(name) => (
                // A missing/unmatched mem is a not-found condition, the
                // same category as `ENTITY_NOT_FOUND` (exit 3) — not a
                // validation refusal. This central engine-error path covers
                // `reload --mem nope` and every command that surfaces the
                // engine's `UnknownMem` rather than constructing the code
                // itself.
                ExitKind::NotFound,
                Some(serde_json::json!({ "name": name })),
            ),
            UnknownRef(raw) => (
                ExitKind::Validation,
                Some(serde_json::json!({ "ref": raw })),
            ),
            BranchResetHeadMoved {
                mem,
                expected,
                current,
            } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "mem": mem,
                    "expected": expected,
                    "current": current,
                })),
            ),
            PushedCommitsProtected {
                mem,
                target_sha,
                pushed_shas,
            } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "mem": mem,
                    "target_sha": target_sha,
                    "pushed_shas": pushed_shas,
                })),
            ),
            UnknownRemote(name) => (
                ExitKind::Validation,
                Some(serde_json::json!({ "remote": name })),
            ),
            LocalDivergence { mem, remote_ref } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "mem": mem,
                    "remote_ref": remote_ref,
                })),
            ),
            NonFastForward { mem, remote } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "mem": mem,
                    "remote": remote,
                })),
            ),
            LocalInvalidState {
                mem,
                remote,
                detail,
            } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "mem": mem,
                    "remote": remote,
                    "detail": detail,
                })),
            ),
            SchemaViolationInFetch {
                mem,
                ref_name,
                violations,
            } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "mem": mem,
                    "ref": ref_name,
                    "violations": violations,
                })),
            ),
            ReadOnlyMount(mem) => (
                ExitKind::Validation,
                Some(serde_json::json!({ "mem": mem })),
            ),
            MemNameCollision {
                name,
                source_origin,
            } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "name": name,
                    "source": source_origin,
                })),
            ),
            SchemaNotFound { mem, pin, sources } => (
                ExitKind::Validation,
                Some(serde_json::json!({ "mem": mem, "pin": pin, "sources": sources })),
            ),
            InvalidInput(msg) => (
                ExitKind::Validation,
                Some(serde_json::json!({ "message": msg })),
            ),
            RenameSimilarityOutOfRange {
                requested,
                allowed_min,
                allowed_max,
            } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "field": "rename_similarity",
                    "requested": requested,
                    "allowed_range": [allowed_min, allowed_max],
                })),
            ),
            // Engine-internal / boundary errors: no user-recoverable
            // structured payload. Code + message are sufficient — the
            // CLI surfaces the typed code via `e.code()` (already set
            // at the top of this fn) and the message text describes
            // the underlying cause.
            DuplicateMem(name) => (ExitKind::Generic, Some(serde_json::json!({ "name": name }))),
            SchemaResolverInit(detail) => (
                ExitKind::Generic,
                Some(serde_json::json!({ "detail": detail })),
            ),
            Mem(detail) => (
                ExitKind::Generic,
                Some(serde_json::json!({ "detail": detail })),
            ),
            ParseAfterWrite(detail) => (
                ExitKind::Generic,
                Some(serde_json::json!({ "detail": detail })),
            ),
            Parse(inner) => (
                ExitKind::Generic,
                Some(serde_json::json!({ "detail": inner.to_string() })),
            ),
            Backend(inner) => (
                ExitKind::Generic,
                Some(serde_json::json!({ "detail": inner.to_string() })),
            ),
            SearchUnavailable => (ExitKind::Generic, Some(serde_json::json!({}))),
            // Typed refusal
            // when `memstead export --format markdown --mem-name <V>`
            // targets a backend that doesn't support markdown
            // regeneration. Validation-class exit code matches other
            // backend-incompatibility refusals.
            MarkdownExportUnsupportedBackend {
                mem,
                active_backend,
                supported_backends,
            } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "mem": mem,
                    "active_backend": active_backend,
                    "supported_backends": supported_backends,
                })),
            ),
            EmptyUpdate { id } => (
                ExitKind::Validation,
                Some(serde_json::json!({
                    "id": id,
                    "recognised_keys": [
                        "sections", "append_sections", "patch_sections",
                        "metadata", "metadata_unset", "declare_relations",
                    ],
                })),
            ),
            // A bad `--since` cursor surfaces the typed `INVALID_CURSOR` (via
            // `e.code()`) with the untruncated SHA — rather than leaking it
            // as the `MEM_ERROR` catch-all.
            InvalidChangesCursor { mem, since } => (
                ExitKind::Validation,
                Some(serde_json::json!({ "mem": mem, "since": since })),
            ),
            // A malformed `anchors[]` element on create/update — typed
            // `INVALID_ANCHOR` (via `e.code()`) with the wrapped anchor
            // error's recovery detail (offending field, bad value, allowed
            // set).
            InvalidAnchor(anchor_err) => (
                ExitKind::Validation,
                Some(serde_json::Value::Object(
                    anchor_err.detail().into_iter().collect(),
                )),
            ),
        };
        // Route the CLI message through the rich-prose renderer so markdown-
        // default mode and `--json --message` consumers see the same
        // fully-inlined recovery prose the MCP text channel emits.
        // The `details` channel is unchanged.
        let message = e.prose_render();
        Self {
            kind,
            code,
            message,
            details,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::output::ExitKind;
    use memstead_base::EngineError;
    use memstead_base::engine::MissingWikiLink;

    /// `DescriptionNotPermitted` must reach the CLI wire as
    /// `code: DESCRIPTION_NOT_PERMITTED` with `ExitKind::Validation`
    /// (exit code 5) and structured details — not `Generic` (exit code
    /// 1) with `details: None`.
    #[test]
    fn from_engine_op_description_not_permitted_carries_validation_and_details() {
        let err = EngineError::DescriptionNotPermitted {
            rel_type: "REFERENCES".to_string(),
            from_id: "demo--source".to_string(),
            to_id: "demo--target".to_string(),
        };
        let cli = CliError::from_engine_op(err);
        assert_eq!(cli.kind, ExitKind::Validation);
        assert_eq!(cli.code, "DESCRIPTION_NOT_PERMITTED");
        let details = cli.details.expect("details must carry structured payload");
        assert_eq!(
            details.get("rel_type").and_then(|v| v.as_str()),
            Some("REFERENCES")
        );
        assert_eq!(
            details.get("from_id").and_then(|v| v.as_str()),
            Some("demo--source")
        );
        assert_eq!(
            details.get("to_id").and_then(|v| v.as_str()),
            Some("demo--target")
        );
    }

    /// `MissingRequiredDescription` shares the same
    /// envelope shape so the agent's branch logic is symmetric.
    #[test]
    fn from_engine_op_missing_required_description_carries_validation_and_details() {
        let err = EngineError::MissingRequiredDescription {
            rel_type: "CHOSEN".to_string(),
            from_id: "decisions--example".to_string(),
            to_id: "specs--target".to_string(),
        };
        let cli = CliError::from_engine_op(err);
        assert_eq!(cli.kind, ExitKind::Validation);
        assert_eq!(cli.code, "MISSING_REQUIRED_DESCRIPTION");
        let details = cli.details.expect("details must carry structured payload");
        assert_eq!(
            details.get("rel_type").and_then(|v| v.as_str()),
            Some("CHOSEN")
        );
    }

    /// `WikiLinkWithoutRelation` already had a typed CLI arm
    /// before the exhaustive-match work (the regression class was
    /// MCP-only), but a smoke test pins the contract so a future
    /// refactor doesn't drop it back into the wildcard.
    #[test]
    fn from_engine_op_wikilink_without_relation_carries_validation_and_missing_list() {
        let err = EngineError::WikiLinkWithoutRelation {
            from_id: "demo--source".to_string(),
            missing: vec![MissingWikiLink {
                section_key: "identity".to_string(),
                target_id: "demo--target".to_string(),
            }],
        };
        let cli = CliError::from_engine_op(err);
        assert_eq!(cli.kind, ExitKind::Validation);
        assert_eq!(cli.code, "WIKILINK_WITHOUT_RELATION");
        let details = cli.details.expect("details must carry structured payload");
        let missing = details
            .get("missing")
            .and_then(|v| v.as_array())
            .expect("details.missing[] must be an array");
        assert_eq!(missing.len(), 1);
        let first = &missing[0];
        assert_eq!(
            first.get("section_key").and_then(|v| v.as_str()),
            Some("identity")
        );
        assert_eq!(
            first.get("target_id").and_then(|v| v.as_str()),
            Some("demo--target")
        );
    }
}