memstead-cli 0.8.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
#![cfg(feature = "mem-repo")]
//! Regression test: recoverable CLI errors never leak `code: "INTERNAL"`.
//!
//! The structural fix (non-optional `CliError.code` and explicit `code`
//! arg on `tool_error_with_payload`) makes "default to INTERNAL"
//! compile-impossible. This test is the runtime cross-check: walks
//! the seven probe-finding commands plus a handful of other
//! recoverable-error CLI invocations and asserts that none of them
//! ships `code: "INTERNAL"` on the JSON wire.
//!
//! Adding a new command that leaks INTERNAL on a recoverable path
//! fails here, forcing the implementer either to type the code or
//! explicitly opt the new path into the genuinely-systemic list
//! (which lives in the source code, not in this test).

use assert_cmd::Command;
use tempfile::TempDir;

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

fn parse_envelope(stdout_bytes: &[u8]) -> serde_json::Value {
    // Under `--json` the error envelope rides stdout so the documented
    // `… --json | jq -r .code` recipe works on the error path.
    let body = std::str::from_utf8(stdout_bytes).expect("stdout must be UTF-8");
    serde_json::from_str(body.trim()).unwrap_or_else(|e| {
        panic!("--json error must parse as JSON: {e}\n--- stdout ---\n{body}\n--- end stdout ---")
    })
}

fn assert_typed_code(envelope: &serde_json::Value, ctx: &str) {
    let code = envelope["code"]
        .as_str()
        .unwrap_or_else(|| panic!("{ctx}: envelope must carry a string `code`, got: {envelope}"));
    assert_ne!(
        code, "INTERNAL",
        "{ctx}: recoverable path must not leak code=INTERNAL — got envelope: {envelope}",
    );
}

/// F5/F15 — `memstead update <missing-id>` returns ENTITY_NOT_FOUND.
#[test]
fn update_missing_entity_returns_typed_code() {
    let tmp = TempDir::new().unwrap();
    let workspace = tmp.path().join("ws");
    memstead()
        .args([
            "mem-repo",
            "init",
            workspace.to_str().unwrap(),
            "--no-gitignore",
        ])
        .assert()
        .success();

    let output = memstead()
        .current_dir(&workspace)
        .args([
            "--json",
            "update",
            "nope--does-not-exist",
            "--section",
            "Body=hi",
            "--auto-hash",
        ])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env = parse_envelope(&output);
    assert_typed_code(&env, "update missing entity");
}

/// F13 — `memstead update <id>` with no hash flag returns HASH_FLAG_REQUIRED.
#[test]
fn update_missing_hash_flag_returns_typed_code() {
    let tmp = TempDir::new().unwrap();
    let workspace = tmp.path().join("ws");
    memstead()
        .args([
            "mem-repo",
            "init",
            workspace.to_str().unwrap(),
            "--no-gitignore",
        ])
        .assert()
        .success();

    let output = memstead()
        .current_dir(&workspace)
        .args(["--json", "update", "anything--here", "--section", "Body=hi"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env = parse_envelope(&output);
    assert_typed_code(&env, "update missing hash flag");
    assert_eq!(
        env["code"], "HASH_FLAG_REQUIRED",
        "expected HASH_FLAG_REQUIRED, got: {env}",
    );
}

/// F21 — `memstead overview --chunk <past-end>` returns CHUNK_OUT_OF_RANGE.
#[test]
fn overview_chunk_past_end_returns_typed_code() {
    let tmp = TempDir::new().unwrap();
    let workspace = tmp.path().join("ws");
    memstead()
        .args([
            "mem-repo",
            "init",
            workspace.to_str().unwrap(),
            "--no-gitignore",
        ])
        .assert()
        .success();

    let output = memstead()
        .current_dir(&workspace)
        .args(["--json", "overview", "--chunk", "99"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env = parse_envelope(&output);
    assert_typed_code(&env, "overview chunk past end");
    assert_eq!(
        env["code"], "CHUNK_OUT_OF_RANGE",
        "expected CHUNK_OUT_OF_RANGE, got: {env}",
    );
}

/// F28 — `memstead init <non-empty>` returns TARGET_NOT_EMPTY.
#[test]
fn init_non_empty_returns_typed_code() {
    let tmp = TempDir::new().unwrap();
    // Drop a file so the target is non-empty before init runs.
    std::fs::write(tmp.path().join("preexisting.md"), "hi").unwrap();

    let output = memstead()
        .args([
            "--json",
            "init",
            "--name",
            "tmp",
            "--schema",
            "default@1.0.0",
            tmp.path().to_str().unwrap(),
        ])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env = parse_envelope(&output);
    assert_typed_code(&env, "init non-empty target");
    assert_eq!(
        env["code"], "TARGET_NOT_EMPTY",
        "expected TARGET_NOT_EMPTY, got: {env}",
    );
}

/// F31 — `memstead type <unknown>` returns UNKNOWN_ENTITY_TYPE.
#[test]
fn type_unknown_returns_typed_code() {
    let tmp = TempDir::new().unwrap();
    let workspace = tmp.path().join("ws");
    memstead()
        .args([
            "mem-repo",
            "init",
            workspace.to_str().unwrap(),
            "--no-gitignore",
        ])
        .assert()
        .success();

    let output = memstead()
        .current_dir(&workspace)
        .args(["--json", "type", "nonexistent-type"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env = parse_envelope(&output);
    assert_typed_code(&env, "type unknown");
}

/// Cold-start probe — running a workspace command outside a workspace
/// returns WORKSPACE_NOT_INITIALISED, not INTERNAL.
#[test]
fn cold_start_returns_typed_code() {
    let tmp = TempDir::new().unwrap();
    let output = memstead()
        .current_dir(tmp.path())
        .args(["--json", "status"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env = parse_envelope(&output);
    assert_typed_code(&env, "status outside workspace");
}

/// `projection migrate` outside a workspace returns the single-sourced
/// WORKSPACE_NOT_INITIALISED code, not INTERNAL.
#[test]
fn projection_migrate_outside_workspace_returns_typed_code() {
    let tmp = TempDir::new().unwrap();
    let output = memstead()
        .current_dir(tmp.path())
        .args(["--json", "projection", "migrate"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env = parse_envelope(&output);
    assert_typed_code(&env, "projection migrate outside workspace");
    assert_eq!(env["code"], "WORKSPACE_NOT_INITIALISED", "got: {env}");
}

/// `projection init` outside a workspace returns the single-sourced
/// WORKSPACE_NOT_INITIALISED code, not INTERNAL.
#[test]
fn projection_init_outside_workspace_returns_typed_code() {
    let tmp = TempDir::new().unwrap();
    let output = memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "projection",
            "init",
            "--mem",
            "m",
            "--source",
            "../x",
            "--medium-type",
            "codebase",
        ])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env = parse_envelope(&output);
    assert_typed_code(&env, "projection init outside workspace");
    assert_eq!(env["code"], "WORKSPACE_NOT_INITIALISED", "got: {env}");
}

/// `projection init` on an existing binding id returns the typed
/// PROJECTION_EXISTS code, not INTERNAL.
#[test]
fn projection_init_existing_binding_returns_typed_code() {
    let tmp = TempDir::new().unwrap();
    let workspace = tmp.path().join("ws");
    memstead()
        .args([
            "mem-repo",
            "init",
            workspace.to_str().unwrap(),
            "--no-gitignore",
        ])
        .assert()
        .success();

    let init_args = [
        "projection",
        "init",
        "--mem",
        "engine",
        "--source",
        "../public",
        "--medium-type",
        "codebase",
        "--name",
        "graph",
    ];
    memstead()
        .current_dir(&workspace)
        .args(init_args)
        .assert()
        .success();

    // Second init on the same id refuses.
    let output = memstead()
        .current_dir(&workspace)
        .args(
            ["--json"]
                .iter()
                .chain(init_args.iter())
                .copied()
                .collect::<Vec<_>>(),
        )
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env = parse_envelope(&output);
    assert_typed_code(&env, "projection init existing binding");
    assert_eq!(env["code"], "PROJECTION_EXISTS", "got: {env}");
}

/// `projection enable` on a missing binding returns the typed
/// PROJECTION_NOT_FOUND code (NotFound exit), not INTERNAL.
#[test]
fn projection_enable_missing_binding_returns_typed_code() {
    let tmp = TempDir::new().unwrap();
    let workspace = tmp.path().join("ws");
    memstead()
        .args([
            "mem-repo",
            "init",
            workspace.to_str().unwrap(),
            "--no-gitignore",
        ])
        .assert()
        .success();

    let output = memstead()
        .current_dir(&workspace)
        .args(["--json", "projection", "enable", "sync", "engine/nope"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env = parse_envelope(&output);
    assert_typed_code(&env, "projection enable missing binding");
    assert_eq!(env["code"], "PROJECTION_NOT_FOUND", "got: {env}");
}

/// `projection advance` on a missing binding returns the typed
/// PROJECTION_NOT_FOUND code (NotFound exit), not INTERNAL — the new leaf is
/// walked here like every other recoverable path.
#[test]
fn projection_advance_missing_binding_returns_typed_code() {
    let tmp = TempDir::new().unwrap();
    let workspace = tmp.path().join("ws");
    memstead()
        .args([
            "mem-repo",
            "init",
            workspace.to_str().unwrap(),
            "--no-gitignore",
        ])
        .assert()
        .success();

    let output = memstead()
        .current_dir(&workspace)
        .args([
            "--json",
            "projection",
            "advance",
            "engine/nope",
            "--dispositions",
            "{}",
        ])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env = parse_envelope(&output);
    assert_typed_code(&env, "projection advance missing binding");
    assert_eq!(env["code"], "PROJECTION_NOT_FOUND", "got: {env}");
}

/// `projection brief` on a missing binding returns the typed
/// PROJECTION_NOT_FOUND code (NotFound exit), not INTERNAL — the brief leaf is
/// walked here like every other recoverable path.
#[test]
fn projection_brief_missing_binding_returns_typed_code() {
    let tmp = TempDir::new().unwrap();
    let workspace = tmp.path().join("ws");
    memstead()
        .args([
            "mem-repo",
            "init",
            workspace.to_str().unwrap(),
            "--no-gitignore",
        ])
        .assert()
        .success();

    let output = memstead()
        .current_dir(&workspace)
        .args(["--json", "projection", "brief", "engine/nope"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env = parse_envelope(&output);
    assert_typed_code(&env, "projection brief missing binding");
    assert_eq!(env["code"], "PROJECTION_NOT_FOUND", "got: {env}");
}

/// `projection migrate` over a dangling ingest→projection ref returns the
/// typed PROJECTION_MIGRATE_DANGLING_REF code, not INTERNAL.
#[test]
fn projection_migrate_dangling_ref_returns_typed_code() {
    let tmp = TempDir::new().unwrap();
    let workspace = tmp.path().join("ws");
    memstead()
        .args([
            "mem-repo",
            "init",
            workspace.to_str().unwrap(),
            "--no-gitignore",
        ])
        .assert()
        .success();

    // A flat ingest naming a projection that does not exist — a dangling ref.
    let ingests = workspace.join(".memstead").join("ingests");
    std::fs::create_dir_all(&ingests).unwrap();
    std::fs::write(
        ingests.join("engine-graph.json"),
        r#"{"projection":"engine/missing","mode":"discovery","trigger":"loop","batch_size":20,"deny_paths":[]}"#,
    )
    .unwrap();

    let output = memstead()
        .current_dir(&workspace)
        .args(["--json", "projection", "migrate"])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env = parse_envelope(&output);
    assert_typed_code(&env, "projection migrate dangling ref");
    assert_eq!(env["code"], "PROJECTION_MIGRATE_DANGLING_REF", "got: {env}");
}

/// Every user-reachable refusal on the `memstead install` flow carries
/// a typed code. The flow is short but every leg of it can fail on
/// ordinary input: a path that is not there, bytes that are not an
/// archive, an archive whose embedded schema will not load, a registry
/// ref for something that was never published, and the workspace-shape
/// gate. None of them may collapse into INTERNAL.
#[test]
fn install_refusals_are_all_typed() {
    let tmp = TempDir::new().unwrap();
    let workspace = tmp.path().join("ws");
    let cache = tmp.path().join("cache");
    memstead()
        .args([
            "mem-repo",
            "init",
            workspace.to_str().unwrap(),
            "--no-gitignore",
        ])
        .assert()
        .success();

    // Not a file.
    let missing = tmp.path().join("nowhere.mem");
    // Not an archive.
    let garbage = tmp.path().join("garbage.mem");
    std::fs::write(&garbage, b"definitely not a zip").unwrap();

    let cases: [(&str, &str); 4] = [
        ("missing local path", missing.to_str().unwrap()),
        ("non-archive bytes", garbage.to_str().unwrap()),
        // The legacy `@scope/name` shape — a user-triggerable input form.
        ("legacy at-scope ref", "@memstead/knowledge"),
        // A path-shaped source that is neither a registry ref nor a file.
        ("directory as source", tmp.path().to_str().unwrap()),
    ];
    for (label, source) in cases {
        let output = memstead()
            .current_dir(&workspace)
            .env("MEMSTEAD_MEM_CACHE", &cache)
            .args(["--json", "install", source])
            .assert()
            .failure()
            .get_output()
            .stdout
            .clone();
        let env = parse_envelope(&output);
        assert_typed_code(&env, &format!("install: {label}"));
    }

    // The workspace-shape gate: a folder workspace has no local schema
    // storage a sealed third-party package could be staged into, so
    // install refuses there — typed, and before any side effect.
    let folder_ws = tmp.path().join("folder-ws");
    std::fs::create_dir_all(folder_ws.join(".memstead")).unwrap();
    std::fs::write(folder_ws.join(".memstead").join("workspace.toml"), "").unwrap();
    let output = memstead()
        .current_dir(&folder_ws)
        .env("MEMSTEAD_MEM_CACHE", &cache)
        .args(["--json", "install", garbage.to_str().unwrap()])
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let env = parse_envelope(&output);
    assert_typed_code(&env, "install into a folder workspace");
}