memstead-cli 0.7.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
//! `memstead create` — create a new entity from flags or a JSON file.
//!
//! Mirrors `memstead_create` in the MCP surface. Two input modes:
//!
//! * **Flags.** `--title`, `--type` (required), plus repeatable
//!   `--section key=value`, `--metadata key=value`, `--relation type:to`.
//! * **JSON file.** `--from payload.json`. Same shape as `memstead_create`'s
//!   `CreateParams`.

use std::path::PathBuf;

use clap::Parser;
use indexmap::IndexMap;
use serde::Deserialize;

use memstead_base::CreateEntityArgs;
#[cfg(feature = "mem-repo")]
use memstead_base::EntityId;
#[cfg(feature = "mem-repo")]
use memstead_base::ops::RelateArg;
use memstead_base::vcs::Actor;

use crate::CliError;
use crate::output::{ExitKind, print_json, print_markdown};
use crate::setup::{CliContext, CliEngine};

#[derive(Parser, Debug)]
#[command(after_long_help = super::create_after_long_help())]
pub struct Args {
    /// Entity title. Required unless `--from` is given.
    #[arg(long)]
    pub title: Option<String>,

    /// Entity type (e.g. `spec`, `memo`, `concept`).
    /// Required unless `--from` is given.
    #[arg(long = "type")]
    pub entity_type: Option<String>,

    /// Mem name. Defaults to the first writable mem.
    #[arg(long)]
    pub mem: Option<String>,

    /// Section content: repeatable `--section key=value`. Body
    /// wiki-links must take slug-form (`[[idempotency]]`, not the
    /// title-case `[[Idempotency]]`) — a non-slug target refuses with
    /// `INVALID_WIKI_LINK_TARGET` carrying a `proposed_slug` to retry with.
    #[arg(long = "section", value_name = "KEY=VALUE")]
    pub sections: Vec<String>,

    /// Metadata override: repeatable `--metadata key=value`.
    #[arg(long = "metadata", value_name = "KEY=VALUE")]
    pub metadata: Vec<String>,

    /// Initial relationship: repeatable `--relation TYPE:target-id`.
    /// Mem-repo workspaces only — on filesystem mems this refuses;
    /// use `memstead relate` after creation there.
    #[arg(long = "relation", value_name = "TYPE:TARGET")]
    pub relations: Vec<String>,

    /// Provenance anchor: repeatable `--anchor '<json>'`, each a JSON
    /// object of the anchor shape (`{ "artifact": "...", "grain": "file",
    /// "class": "anchored", "hash": "...", "hash_stability": "stable" }`).
    /// Written into the mem-branch anchors sidecar in the same commit as
    /// the entity. A malformed anchor refuses `INVALID_ANCHOR`. Ignored
    /// when `--from` is given (the file's `anchors[]` is authoritative).
    #[arg(long = "anchor", value_name = "JSON")]
    pub anchors: Vec<String>,

    /// JSON file matching the MCP `memstead_create` args shape. If set,
    /// all `--title` / `--type` / `--section` / `--metadata` / `--relation`
    /// / `--anchor` flags are ignored (the file is the single source of truth).
    /// `--note` still applies (winning over the file's `note`), and
    /// `--dry-run` ORs with the file's `dry_run` — same semantics as
    /// `update --from`, so one template feeds both commands.
    /// The JSON type field is `entity_type` (not `type`), matching the
    /// response envelopes — a previous `--json` response pipes back in
    /// unchanged.
    #[arg(long = "from", value_name = "FILE")]
    pub from: Option<PathBuf>,

    /// Preview only — validate and compute the result without writing to
    /// disk, mutating the store, or producing a commit. Response carries
    /// the prospective id / file_path / content_hash plus any warnings.
    /// MEM-REPO WORKSPACES ONLY — refused with `INVALID_INPUT` on the
    /// filesystem-mem workspace `memstead quickstart` produces.
    #[arg(long = "dry-run")]
    pub dry_run: bool,

    /// Agent-authored provenance note (≤280 chars, one sentence
    /// describing why this mutation happened). Lands in the per-mem
    /// commit body between the mechanical subject line and the
    /// provenance trailers. When `[mutations].require_notes = true` in
    /// workspace config a missing note adds a `NOTE_MISSING` warning
    /// to the response (the mutation still commits). When `--from` also
    /// carries a `note`, this flag takes precedence.
    #[arg(long)]
    pub note: Option<String>,
}

/// On-disk JSON payload shape — mirrors MCP `CreateParams` exactly.
///
/// The type field is `entity_type`, matching the response envelopes
/// every read/write surface emits, so an agent can pipe a previous
/// `memstead create --json` response back through `--from` for a
/// follow-up create without renaming the field.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct CreatePayload {
    title: String,
    entity_type: String,
    mem: Option<String>,
    #[serde(default)]
    sections: IndexMap<String, String>,
    #[serde(default)]
    metadata: IndexMap<String, String>,
    #[serde(default)]
    relations: Vec<RelationPayload>,
    /// Provenance anchors — matches the MCP `memstead_create` `anchors[]`
    /// shape. Each element is validated engine-side into a typed
    /// `INVALID_ANCHOR` refusal on malformed input.
    #[serde(default)]
    anchors: Vec<memstead_base::anchor::AnchorInput>,
    /// Agent-authored provenance note — matches the MCP `memstead_create`
    /// shape's `note`. Optional; the command-line `--note` takes
    /// precedence when both are supplied.
    #[serde(default)]
    note: Option<String>,
    /// Preview-only marker — OR-ed with the `--dry-run` flag, same
    /// semantics as `update --from`. One JSON template can therefore
    /// feed both `create --from` and `update --from`. The
    /// optimistic-locking selectors (`auto_hash`, `force`) are
    /// deliberately flag-only on both commands: a stored payload must
    /// never be able to disable locking on a future run.
    #[serde(default)]
    dry_run: bool,
    /// Tolerated for template symmetry with `update --from` (one JSON
    /// document feeds both commands). Create derives the entity id
    /// from the title, so a supplied `id` is only *checked*: a value
    /// whose slug part does not match the derived slug refuses with
    /// `INVALID_INPUT` rather than silently landing elsewhere.
    #[serde(default)]
    id: Option<String>,
    /// Tolerated for template symmetry with `update --from`. Create
    /// has no stored state to compare a hash against; the value is
    /// ignored (documented, not silent — this doc is the statement).
    #[serde(default)]
    #[allow(dead_code)]
    expected_hash: Option<String>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
#[cfg_attr(not(feature = "mem-repo"), allow(dead_code))]
struct RelationPayload {
    to: String,
    #[serde(rename = "type")]
    rel_type: String,
    #[serde(default)]
    description: Option<String>,
}

pub fn run(ctx: &CliContext, args: Args) -> anyhow::Result<()> {
    let payload = if let Some(ref file) = args.from {
        let bytes = std::fs::read(file).map_err(|e| {
            CliError::new(
                ExitKind::Generic,
                "INVALID_INPUT",
                format!("failed to read {}: {e}", file.display()),
            )
        })?;
        let mut parsed: CreatePayload = serde_json::from_slice(&bytes).map_err(|e| {
            CliError::new(
                ExitKind::Validation,
                "INVALID_INPUT",
                format!("invalid JSON in {}: {e}", file.display()),
            )
            .with_details(serde_json::json!({
                "path": file.display().to_string(),
                "parser_error": e.to_string(),
            }))
        })?;
        // `--dry-run` and the file's `dry_run` OR — same semantics as
        // `update --from`; the flag can force a preview, never disable one.
        parsed.dry_run |= args.dry_run;
        parsed
    } else {
        let title = args.title.clone().ok_or_else(|| {
            CliError::new(
                ExitKind::Validation,
                "INVALID_INPUT",
                "missing --title (or pass --from <file.json>)",
            )
        })?;
        let entity_type = args.entity_type.clone().ok_or_else(|| {
            CliError::new(
                ExitKind::Validation,
                "INVALID_INPUT",
                "missing --type (or pass --from <file.json>)",
            )
        })?;
        CreatePayload {
            title,
            entity_type,
            mem: args.mem.clone(),
            sections: parse_kv_list(&args.sections, "--section")?,
            metadata: parse_kv_list(&args.metadata, "--metadata")?,
            relations: parse_relation_list(&args.relations)?,
            anchors: parse_anchor_list(&args.anchors)?,
            note: None,
            dry_run: args.dry_run,
            id: None,
            expected_hash: None,
        }
    };

    // `dry_run` is settled at payload level (file OR flag) — read it
    // from here on, never from `args`, so the `--from` file's value
    // is honoured on every branch below.
    let dry_run = payload.dry_run;

    // Template-symmetry `id` consistency check: create derives its id
    // from the title, so a template `id` must agree with the derived
    // slug — catching template drift instead of silently creating a
    // second entity beside the intended one. `expected_hash` is
    // tolerated and ignored (nothing exists yet to compare against).
    if let Some(template_id) = payload.id.as_deref() {
        let derived = memstead_base::entity::id::validate_and_derive_slug(&payload.title)
            .map_err(|e| CliError::new(ExitKind::Validation, "INVALID_TITLE", e.to_string()))?;
        let derived_slug = derived.slug;
        let slug_part = template_id
            .rsplit_once("--")
            .map(|(_, s)| s)
            .unwrap_or(template_id);
        if slug_part != derived_slug {
            return Err(CliError::new(
                ExitKind::Validation,
                "INVALID_INPUT",
                format!(
                    "template `id` {template_id:?} does not match the id derived from the \
                     title (slug {derived_slug:?}) — create derives identity from the title; \
                     fix the template's id or title"
                ),
            )
            .into());
        }
    }

    // `--note` (CLI flag) wins over a `note` carried in the `--from`
    // payload when both are present; otherwise the file's note is used.
    let note = args.note.clone().or_else(|| payload.note.clone());

    match ctx.cli_engine()? {
        #[cfg(feature = "mem-repo")]
        CliEngine::MemRepo(mut engine) => {
            let mem = match payload.mem {
                Some(v) => v,
                None => first_writable_mem(&engine)?,
            };

            let create_args = CreateEntityArgs {
                anchors: payload.anchors,
                title: payload.title,
                mem,
                entity_type: payload.entity_type,
                sections: payload.sections,
                metadata: payload.metadata,
                relations: payload
                    .relations
                    .into_iter()
                    .map(|r| RelateArg {
                        to: EntityId::canonical(&r.to),
                        rel_type: r.rel_type,
                        description: r.description,
                    })
                    .collect(),
                dry_run,
            };

            let result = engine
                .create_entity_with_ctx(create_args, &crate::setup::cli_ctx_with_note(note.clone()))
                .map_err(CliError::from_engine_op)?;
            let mem_changed = engine.take_mem_changed_notices();

            if ctx.json {
                let mut body = serde_json::to_value(&result).unwrap_or(serde_json::Value::Null);
                super::merge_mem_changed_json(&mut body, &mem_changed);
                print_json(&body)?;
            } else {
                let warnings = if result.warnings.is_empty() {
                    String::new()
                } else {
                    let rendered: Vec<String> =
                        result.warnings.iter().map(ToString::to_string).collect();
                    let warnings_block =
                        format!("\n\n> warnings:\n> - {}", rendered.join("\n> - "),);
                    let guidance_block = super::render_type_guidance_block(&result.type_guidance);
                    format!("{warnings_block}{guidance_block}")
                };
                let incoming_block = if result.incoming.is_empty() {
                    String::new()
                } else {
                    let heading = if dry_run {
                        format!("Would adopt incoming edges ({})", result.incoming.len())
                    } else {
                        format!("Adopted incoming edges ({})", result.incoming.len())
                    };
                    let rows: Vec<String> = result
                        .incoming
                        .iter()
                        .map(|r| {
                            format!("- {} --[{}]--> (this) [{}]", r.from, r.rel_type, r.source)
                        })
                        .collect();
                    format!("\n\n## {}\n\n{}", heading, rows.join("\n"))
                };
                let title_heading = if dry_run {
                    format!("Dry run — would create `{}`", result.id)
                } else {
                    format!("Created `{}`", result.id)
                };
                let mem_changed_block = super::render_mem_changed_block(&mem_changed);
                print_markdown(&format!(
                    "# {}\n\n- Title: {}\n- Mem: {}\n- File: {}\n- Hash: `{}`{}{}{}",
                    title_heading,
                    result.title,
                    result.mem,
                    result.file_path,
                    result.content_hash,
                    warnings,
                    incoming_block,
                    mem_changed_block,
                ));
            }
        }
        CliEngine::Filesystem(mut engine) => {
            // Filesystem-mem `memstead create` accepts `--mem` for shape
            // parity (matches mem-repo CLI), but the engine is single-
            // mem; an explicit `--mem` mismatch with the workspace's
            // pinned mem errors out so the user sees the misconfig
            // rather than a silent no-op.
            let workspace_mem = engine
                .mem_names()
                .into_iter()
                .next()
                .map(String::from)
                .unwrap_or_default();
            if let Some(requested) = payload.mem.as_deref()
                && requested != workspace_mem
            {
                return Err(CliError::new(
                        ExitKind::NotFound,
                        "UNKNOWN_MEM",
                        format!(
                            "filesystem-mem is single-mem: workspace mem is `{workspace_mem}`, request specified `{requested}`"
                        ),
                    )
                    .into());
            }
            // `--relation` and `--dry-run` are not yet honoured on the
            // filesystem path — the unified `Engine::create_entity`
            // surface accepts neither. Surface that as a clear
            // validation error rather than silently dropping the flags.
            if !payload.relations.is_empty() {
                return Err(CliError::new(
                    ExitKind::Validation,
                    "INVALID_INPUT",
                    "--relation is not yet supported on filesystem-mem `memstead create` — use `memstead relate` after creation",
                )
                .into());
            }
            if dry_run {
                return Err(CliError::new(
                    ExitKind::Validation,
                    "INVALID_INPUT",
                    "--dry-run is not yet supported on filesystem-mem `memstead create`",
                )
                .into());
            }

            let create_args = CreateEntityArgs {
                anchors: payload.anchors,
                mem: workspace_mem,
                title: payload.title.clone(),
                entity_type: payload.entity_type,
                sections: payload.sections,
                metadata: payload.metadata,
                relations: Vec::new(),
                dry_run: false,
            };
            let outcome = engine
                .create_entity(
                    create_args,
                    Actor::Cli,
                    Some(&crate::setup::cli_client_id()),
                    note.as_deref(),
                )
                .map_err(CliError::from_engine_op)?;

            if ctx.json {
                // WarningHint's Serialize impl produces the
                // `{code, message, details}` envelope that full
                // already used, so the wire shape is unchanged.
                print_json(&serde_json::json!({
                    "id": outcome.id.as_ref(),
                    "title": payload.title,
                    "file_path": outcome.file_path,
                    "_hash": outcome.content_hash,
                    "warnings": outcome.warnings,
                    "type_guidance": outcome.type_guidance,
                }))?;
            } else {
                let warnings = if outcome.warnings.is_empty() {
                    String::new()
                } else {
                    // WarningHint's Display impl renders human-
                    // readable text per variant.
                    let rendered: Vec<String> =
                        outcome.warnings.iter().map(|w| w.to_string()).collect();
                    let warnings_block =
                        format!("\n\n> warnings:\n> - {}", rendered.join("\n> - "),);
                    let guidance_block = super::render_type_guidance_block(&outcome.type_guidance);
                    format!("{warnings_block}{guidance_block}")
                };
                print_markdown(&format!(
                    "# Created `{}`\n\n- Title: {}\n- Mem: {}\n- File: {}\n- Hash: `{}`{}",
                    outcome.id,
                    payload.title,
                    outcome.id.mem(),
                    outcome.file_path,
                    outcome.content_hash,
                    warnings,
                ));
            }
        }
    }
    Ok(())
}

fn parse_kv_list(items: &[String], flag: &str) -> anyhow::Result<IndexMap<String, String>> {
    let mut out = IndexMap::with_capacity(items.len());
    for raw in items {
        let (k, v) = raw.split_once('=').ok_or_else(|| {
            CliError::new(
                ExitKind::Validation,
                "INVALID_INPUT",
                format!("{flag}: expected KEY=VALUE, got `{raw}`"),
            )
        })?;
        out.insert(k.to_string(), v.to_string());
    }
    Ok(out)
}

/// Parse repeated `--anchor '<json>'` flag values into engine
/// `AnchorInput`s. Each value is a JSON object of the anchor shape; a
/// syntactically-broken JSON is a CLI input error, while a well-formed but
/// semantically-invalid anchor (unknown class/grain, etc.) flows through
/// to the engine's typed `INVALID_ANCHOR` refusal at mutation time.
pub(crate) fn parse_anchor_list(
    items: &[String],
) -> anyhow::Result<Vec<memstead_base::anchor::AnchorInput>> {
    let mut out = Vec::with_capacity(items.len());
    for raw in items {
        let anchor: memstead_base::anchor::AnchorInput =
            serde_json::from_str(raw).map_err(|e| {
                CliError::new(
                    ExitKind::Validation,
                    "INVALID_INPUT",
                    format!("--anchor: expected a JSON anchor object, got `{raw}`: {e}"),
                )
            })?;
        out.push(anchor);
    }
    Ok(out)
}

fn parse_relation_list(items: &[String]) -> anyhow::Result<Vec<RelationPayload>> {
    let mut out = Vec::with_capacity(items.len());
    for raw in items {
        let (rel_type, to) = raw.split_once(':').ok_or_else(|| {
            CliError::new(
                ExitKind::Validation,
                "INVALID_INPUT",
                format!("--relation: expected TYPE:target-id, got `{raw}`"),
            )
        })?;
        out.push(RelationPayload {
            rel_type: rel_type.to_string(),
            to: to.to_string(),
            description: None,
        });
    }
    Ok(out)
}

#[cfg(feature = "mem-repo")]
fn first_writable_mem(engine: &memstead_base::Engine) -> anyhow::Result<String> {
    // Resolve through the shared stable-default contract so the CLI and
    // MCP omitted-`mem` paths always agree: the first writable mount in
    // declaration order — the seed mem — not an alphabetically-first or
    // set-order pick that shifts when an unrelated mem is added.
    match engine.default_writable_mem() {
        Some(name) => Ok(name.to_string()),
        None => Err(CliError::new(
            ExitKind::Generic,
            "NO_WRITABLE_MEM",
            "no writable mem loaded — pass --mem <name>",
        )
        .into()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The `--from` payload accepts a top-level `note`, matching the MCP
    /// `memstead_create` shape the help text claims parity with. A payload
    /// without `note` still deserialises (the field is optional).
    #[test]
    fn create_payload_accepts_optional_note() {
        let with_note: CreatePayload =
            serde_json::from_str(r#"{"title":"X","entity_type":"spec","note":"why this landed"}"#)
                .expect("payload with note must parse");
        assert_eq!(with_note.note.as_deref(), Some("why this landed"));

        let without: CreatePayload = serde_json::from_str(r#"{"title":"X","entity_type":"spec"}"#)
            .expect("note-less payload must still parse");
        assert!(without.note.is_none());
    }

    /// `--note` (CLI flag) takes precedence over a `note` in the file;
    /// the file's note is used only when the flag is absent.
    #[test]
    fn cli_note_takes_precedence_over_file_note() {
        let cli = Some("from-flag".to_string());
        let file = Some("from-file".to_string());
        assert_eq!(
            cli.clone().or_else(|| file.clone()).as_deref(),
            Some("from-flag")
        );
        assert_eq!(None.or_else(|| file.clone()).as_deref(), Some("from-file"));
    }
}