memstead-cli 0.2.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
#![cfg(feature = "mem-repo")]
//! Integration tests for `memstead` read subcommands.
//!
//! Each test sets up a fresh temp mem with one or two entities and runs the
//! binary as a subprocess. Tests cover: default markdown output, `--json`
//! output, and typed exit codes.

use std::fs;
use std::path::Path;

use assert_cmd::Command;
use memstead_git_branch::test_support::init_real_mem_repo_from_disk;
use predicates::prelude::*;
use predicates::str::contains;
use tempfile::TempDir;

/// Seed a canonical `cli-test/` mem dir under `root`. Returns the
/// mem's absolute path. The dir basename equals the declared
/// `name: "cli-test"` so the engine's basename-invariant holds.
///
/// Also lays down `<root>/mem-repo/.git/` so the engine's
/// `mem-repo/.git/` fail-fast accepts the workspace and so
/// `find_workspace_root` (the CLI's walk-up) resolves `<root>` as the
/// workspace.
fn seed_cli_test_mem(root: &Path) -> std::path::PathBuf {
    let dir = root.join("cli-test");
    fs::create_dir_all(&dir).unwrap();
    make_test_mem(&dir);
    init_real_mem_repo_from_disk(root, &[(&dir, "cli-test")]);
    dir
}

/// Write a minimal single-type mem with one basic entity into `dir`.
fn make_test_mem(dir: &Path) {
    let store = dir.join(".memstead");
    fs::create_dir_all(&store).unwrap();
    fs::write(
        store.join("config.json"),
        r#"{ "schema": "default@1.0.0" }"#,
    )
    .unwrap();

    fs::write(
        dir.join("alpha.md"),
        r#"---
type: spec
created_date: 2026-01-01
last_modified: 2026-01-01
level: M0
---
# Alpha

## Identity

The alpha entity used to exercise CLI read commands.

## Purpose

Verifies memstead CLI integration end-to-end.

## Relationships

- **USES**: [[beta]]
"#,
    )
    .unwrap();

    fs::write(
        dir.join("beta.md"),
        r#"---
type: spec
created_date: 2026-01-02
last_modified: 2026-01-02
level: M0
---
# Beta

## Identity

The beta entity, used by alpha via USES.

## Purpose

Provides a second entity so relations and path commands have something to trace.
"#,
    )
    .unwrap();
}

fn memstead() -> Command {
    Command::cargo_bin("memstead").expect("memstead binary must be built by cargo")
}

#[test]
fn stats_markdown() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .arg("stats")
        .assert()
        .success()
        .stdout(contains("# Graph stats"))
        .stdout(contains("Nodes: 2"));
}

/// Smoke-test Bug 2 closure for `memstead stats` on a filesystem-mem
/// workspace. Pre-CLI-parity, this command would error out with the
/// "No mems found. Run `memstead mem-repo init`" message; post the
/// `CliEngine` foundation the command dispatches into the unified
/// `memstead_base::Engine` (lean path) and emits the same shape the
/// mem-repo path produces.
#[test]
fn stats_works_on_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    // `memstead init --name demo --schema default@1.0.0` lays down
    // `.memstead/config.json` plus the empty cache / memstead-io subdirs.
    memstead()
        .current_dir(tmp.path())
        .args(["init", "--name", "demo", "--schema", "default@1.0.0"])
        .assert()
        .success();

    // Empty filesystem-mem has zero entities — the command must
    // still produce the canonical markdown layout, not bail.
    memstead()
        .current_dir(tmp.path())
        .arg("stats")
        .assert()
        .success()
        .stdout(contains("# Graph stats"))
        .stdout(contains("Nodes: 0"));
}

#[test]
fn stats_json() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    let output = memstead()
        .current_dir(tmp.path())
        .args(["--json", "stats"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let parsed: serde_json::Value = serde_json::from_slice(&output).expect("valid JSON");
    assert_eq!(parsed["total_nodes"], 2);
    assert_eq!(parsed["real_nodes"], 2);
}

#[test]
fn entity_markdown() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .args(["entity", "cli-test--alpha"])
        .assert()
        .success()
        .stdout(contains("# Alpha"))
        .stdout(contains("## Identity"))
        .stdout(contains("_hash:"));
}

/// Helper: lay down a filesystem-mem workspace at `tmp` with one
/// entity hand-shaped as `demo--alpha`. Returns the path to the
/// workspace root. Used by the suite of filesystem-mem dispatch
/// tests for read-side subcommands.
fn seed_filesystem_mem(tmp: &TempDir) {
    memstead()
        .current_dir(tmp.path())
        .args(["init", "--name", "demo", "--schema", "default@1.0.0"])
        .assert()
        .success();
    fs::write(
        tmp.path().join("alpha.md"),
        r#"---
type: spec
created_date: 2026-01-01
last_modified: 2026-01-01
level: M0
---
# Alpha

## Identity

A filesystem-mem entity exercising CLI parity.

## Purpose

Lets the read-side CLI commands round-trip without the mem-repo path.
"#,
    )
    .unwrap();
}

#[test]
fn list_works_on_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    seed_filesystem_mem(&tmp);

    memstead()
        .current_dir(tmp.path())
        .arg("list")
        .assert()
        .success()
        .stdout(contains("demo--alpha"));
}

#[test]
fn search_works_on_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    seed_filesystem_mem(&tmp);

    memstead()
        .current_dir(tmp.path())
        .args(["search", "Alpha"])
        .assert()
        .success()
        .stdout(contains("Alpha"));
}

#[test]
fn relations_works_on_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    seed_filesystem_mem(&tmp);

    memstead()
        .current_dir(tmp.path())
        .args(["relations", "demo--alpha"])
        .assert()
        .success()
        .stdout(contains("demo--alpha"));
}

#[test]
fn overview_works_on_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    seed_filesystem_mem(&tmp);

    memstead()
        .current_dir(tmp.path())
        .arg("overview")
        .assert()
        .success();
}

/// `overview --json`
/// promotes `overview_mode`, `total_chunks`, and `hints` to structured
/// envelope siblings so a consumer branches on the mode / fetches the
/// next chunk without parsing the `markdown` string. The `markdown`
/// field stays present (promotion is additive).
#[test]
fn overview_json_promotes_mode_chunks_and_hints_as_siblings() {
    let tmp = TempDir::new().unwrap();
    seed_filesystem_mem(&tmp);

    let output = memstead()
        .current_dir(tmp.path())
        .args(["--json", "overview"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let parsed: serde_json::Value = serde_json::from_slice(&output).expect("valid JSON");

    assert!(
        parsed.get("markdown").and_then(|v| v.as_str()).is_some(),
        "markdown field must remain for the human-rendered view: {parsed}"
    );
    let mode = parsed
        .get("overview_mode")
        .and_then(|v| v.as_str())
        .expect("overview_mode promoted as a sibling");
    assert!(
        matches!(mode, "complete" | "reduced" | "overbudget"),
        "overview_mode must be a known value, got: {mode}"
    );
    assert!(
        parsed
            .get("total_chunks")
            .and_then(|v| v.as_u64())
            .is_some(),
        "total_chunks must be a numeric sibling: {parsed}"
    );
    assert!(
        parsed.get("hints").map(|v| v.is_array()).unwrap_or(false),
        "hints must be an array sibling: {parsed}"
    );
}

#[test]
fn context_works_on_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    seed_filesystem_mem(&tmp);

    memstead()
        .current_dir(tmp.path())
        .args(["context", "demo--alpha"])
        .assert()
        .success();
}

#[test]
fn health_works_on_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    seed_filesystem_mem(&tmp);

    memstead()
        .current_dir(tmp.path())
        .arg("health")
        .assert()
        .success()
        .stdout(contains("# Graph health"));
}

/// `memstead entity <id>` on a filesystem-mem workspace dispatches via
/// the `CliEngine::Filesystem` arm and reads the entity from the
/// directory walk. Pre-CLI-parity this errored with the
/// "No mems found" bail; post the foundation it round-trips.
#[test]
fn entity_works_on_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    memstead()
        .current_dir(tmp.path())
        .args(["init", "--name", "demo", "--schema", "default@1.0.0"])
        .assert()
        .success();

    // Drop a hand-shaped entity .md so the engine's directory walk
    // picks it up on init. Avoids a `memstead create` round-trip until
    // that command also dispatches through `CliEngine`.
    fs::write(
        tmp.path().join("alpha.md"),
        r#"---
type: spec
created_date: 2026-01-01
last_modified: 2026-01-01
level: M0
---
# Alpha

## Identity

A filesystem-mem entity exercising CLI parity.

## Purpose

Lets `memstead entity` round-trip without the mem-repo path.
"#,
    )
    .unwrap();

    memstead()
        .current_dir(tmp.path())
        .args(["entity", "demo--alpha"])
        .assert()
        .success()
        .stdout(contains("# Alpha"))
        .stdout(contains("## Identity"))
        .stdout(contains("_hash:"));
}

#[test]
fn entity_not_found_exit_code_3() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .args(["entity", "cli-test--does-not-exist"])
        .assert()
        .failure()
        .code(3)
        .stderr(contains("Entity not found"));
}

/// A missing/unmatched `--mem` is a not-found condition — exit 3 on
/// every command, the same bucket as the `entity <missing>` precedent
/// above. Locks the uniform `UNKNOWN_MEM` → `NotFound` mapping across
/// the read-scoped read path (`search`/`list`), `changes`, and the
/// engine-error path (`reload`). Measured standalone, not through a
/// pipe — a pipe would mask the exit through the last process.
#[test]
fn unknown_mem_exit_code_3() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    for args in [
        vec!["search", "x", "--mem", "nope"],
        vec!["list", "--mem", "nope"],
        vec!["reload", "--mem", "nope"],
        vec!["changes", "--since", "HEAD", "--mem", "nope"],
    ] {
        memstead()
            .current_dir(tmp.path())
            .args(&args)
            .assert()
            .failure()
            .code(3);
    }
}

#[test]
fn entity_not_found_json_envelope() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    let assert = memstead()
        .current_dir(tmp.path())
        .args(["--json", "entity", "cli-test--does-not-exist"])
        .assert()
        .failure()
        .code(3);
    // Under `--json` the error envelope rides stdout
    // so `… --json | jq -r .code` works on the error path.
    let stdout = String::from_utf8(assert.get_output().stdout.clone()).unwrap();
    let envelope: serde_json::Value = serde_json::from_str(stdout.trim()).expect("JSON envelope");
    // Wire shape: `{code, message, details}` matching MCP. Process exit
    // stays at the NotFound exit-kind (numeric 3) but it rides on the
    // process-status channel rather than inside the JSON body.
    assert_eq!(envelope["code"], "ENTITY_NOT_FOUND");
    assert!(
        envelope["message"]
            .as_str()
            .unwrap()
            .contains("Entity not found")
    );
}

#[test]
fn relations_markdown() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .args(["relations", "cli-test--alpha"])
        .assert()
        .success()
        .stdout(contains("## Outgoing"))
        .stdout(contains("USES"));
}

#[test]
fn search_finds_entity() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .args(["search", "alpha"])
        .assert()
        .success()
        .stdout(contains("Alpha"));
}

#[test]
fn list_all() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .arg("list")
        .assert()
        .success()
        .stdout(contains("Alpha"))
        .stdout(contains("Beta"));
}

#[test]
fn overview_runs() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .arg("overview")
        .assert()
        .success();
}

/// Full CLI's overview command renders the rich content (community
/// bridges, mem distribution, dangling links) via the shared
/// `memstead-engine::overview::compose_overview` composer. The full CLI
/// renders the content directly: when `--include` is passed the
/// `OVERVIEW_RICH_CONTENT_PRO_ONLY` (formerly `mcp_only_notice`)
/// warning string must not appear in the response.
#[test]
fn overview_with_include_renders_rich_content_without_pro_only_warning() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .args([
            "overview",
            "--include",
            "mem_distribution,community_bridges,dangling_links",
        ])
        .assert()
        .success()
        .stdout(contains("## Schemas"))
        .stdout(contains("## Mems"))
        // The lean CLI's pre-lift output would have included this
        // warning code; the full CLI's shared-composer path does NOT.
        .stdout(predicates::str::contains("OVERVIEW_RICH_CONTENT_PRO_ONLY").not())
        // Full CLI uses `memstead type <name>` for the schema-lookup hint,
        // not the MCP-flavour `memstead_schema(name=...)`.
        .stdout(contains("`memstead type <name>`"));
}

#[test]
fn type_named() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .args(["type", "spec"])
        .assert()
        .success()
        .stdout(contains("# Type: spec"))
        .stdout(contains("## Sections"));
}

#[test]
fn health_summary() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .arg("health")
        .assert()
        .success()
        .stdout(contains("# Graph health"))
        .stdout(contains("Entities: 2"));
}

/// Seed a workspace whose mem uses a custom schema with one
/// `required_outgoing` block (decision needs CHOSEN). When
/// `with_violation` is true, a single decision entity is authored
/// without any CHOSEN edge so `memstead_health
/// include=missing_required_outgoing` reports one violator;
/// otherwise the mem has no entities and the report is empty.
fn seed_strict_health_workspace(root: &Path, with_violation: bool) {
    // Authored schema at the fixed folder-backend location
    // (`<workspace>/.memstead/schemas/`); the `schemas_dir` key is retired.
    let schema_dir = root
        .join(".memstead")
        .join("schemas")
        .join("strictdecision");
    fs::create_dir_all(schema_dir.join("types")).unwrap();
    fs::write(
        schema_dir.join("schema.yaml"),
        r#"name: strictdecision
version: 0.1.0
description: Minimal schema pinning required_outgoing for the CLI --strict test.
when_to_use: Used only by memstead-cli health-strict integration tests.
types:
  - decision
relationships:
  mode: strict
  definitions:
    - name: PART_OF
      description: hierarchy
      default_weight: 3.0
      acyclic: true
    - name: REFERENCES
      description: inline link
      default_weight: 0.5
    - name: CHOSEN
      description: decision picked option
      default_weight: 3.0
    - name: _default
      description: fallback
      default_weight: 1.0
community:
  resolution: 1.0
  seed: 42
"#,
    )
    .unwrap();
    fs::write(
        schema_dir.join("types").join("decision.yaml"),
        r#"name: decision
description: A choice with required CHOSEN edge.
when_to_use: tests
sections:
  - key: body
    heading: Body
    required: true
    search_weight: 10.0
    catch_all: true
    write_rules: []
metadata_fields: []
title_weight: 100.0
text_fields:
  - body
hierarchy_relationship: PART_OF
propagating_relationships: []
updatable_fields:
  - title
  - body
health_required_fields:
  - body
staleness_threshold_days: 90
write_rules: []
required_outgoing:
  - relationships: [CHOSEN]
    cardinality: at_least_one
"#,
    )
    .unwrap();

    let mem_dir = root.join("strictmem");
    fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
    fs::write(
        mem_dir.join(".memstead").join("config.json"),
        r#"{ "schema": "strictdecision@0.1.0" }"#,
    )
    .unwrap();

    if with_violation {
        fs::write(
            mem_dir.join("violator.md"),
            r#"---
type: decision
created_date: 2026-01-01
last_modified: 2026-01-01
---
# Violator

## Body

A decision entity authored without any CHOSEN edge — exercises the
`MISSING_REQUIRED_OUTGOING` health surface.
"#,
        )
        .unwrap();
    }

    init_real_mem_repo_from_disk(root, &[(&mem_dir, "strictmem")]);
}

#[test]
fn health_strict_exits_zero_when_no_violations() {
    let tmp = TempDir::new().unwrap();
    seed_strict_health_workspace(tmp.path(), false);

    memstead()
        .current_dir(tmp.path())
        .args([
            "health",
            "--include",
            "missing_required_outgoing",
            "--strict",
        ])
        .assert()
        .success();
}

#[test]
fn health_strict_exits_one_when_violations_present() {
    let tmp = TempDir::new().unwrap();
    seed_strict_health_workspace(tmp.path(), true);

    let assert = memstead()
        .current_dir(tmp.path())
        .args([
            "health",
            "--include",
            "missing_required_outgoing",
            "--strict",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(contains("strict mode"))
        .stderr(contains("missing_required_outgoing: 1"));
    let stdout = String::from_utf8(assert.get_output().stdout.clone()).unwrap();
    assert!(
        stdout.contains("Missing required outgoing"),
        "violation report still rendered to stdout before non-zero exit; got:\n{stdout}"
    );
}