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
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
//! `memstead quickstart` — the batteries-included cold start.
//!
//! One run in a fresh (or trivially-dirty) directory leaves: a bootable
//! filesystem-mem workspace pinned to the default schema, one seed
//! entity so the graph is non-empty, and the MCP wiring for the
//! selected agent targets. Output names each artifact plus the single
//! next action.
//!
//! Contract split against `memstead init`: `init` is the deliberate,
//! script-safe verb — exact pins, strict emptiness, no side effects
//! beyond `.memstead/`. `quickstart` is the newcomer verb — it derives
//! the mem name from the directory, tolerates dotfiles and
//! README-grade files, and writes agent config. It composes the same
//! engine primitives (`init_filesystem_mem`, `Engine::create_entity`)
//! rather than forking a second init path; the write-validation
//! strictness downstream of the doorway is untouched.
//!
//! Interactivity ceiling: two prompts, both TTY-only, both with a flag
//! alternative — the agent-target selection (`--agent` bypasses) and
//! the mem name when derivation from the directory fails (`--name`
//! bypasses). Non-interactive runs never block: no `--agent` defaults
//! to Claude Code (and says so), an underivable name refuses with the
//! exact command to run instead.

use std::io::{IsTerminal, Write as _};
use std::path::{Path, PathBuf};

use clap::{Args as ClapArgs, ValueEnum};
use memstead_base::filesystem::config::{config_path, init_filesystem_mem, validate_mem_name};
use memstead_base::vcs::Actor;
use memstead_base::{CreateEntityArgs, Engine as BaseEngine};
use serde_json::json;

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

use super::init::find_ancestor_workspace;

/// `memstead quickstart` arguments.
#[derive(ClapArgs, Debug)]
pub struct Args {
    /// Target folder. Defaults to the current working directory.
    #[arg(value_name = "PATH")]
    pub path: Option<PathBuf>,

    /// Mem name. Normally derived from the directory name; pass this
    /// when the derivation fails (or to override it). Slug-shaped:
    /// `^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$`.
    #[arg(long)]
    pub name: Option<String>,

    /// Agent target(s) to write MCP wiring for. Repeatable. Skips the
    /// interactive selection prompt. Without a TTY and without this
    /// flag, quickstart defaults to `claude-code`.
    #[arg(long = "agent", value_enum)]
    pub agents: Vec<AgentTarget>,
}

/// The supported agent targets and the wiring each one gets. The three
/// file-writing targets take project-scoped MCP config; Codex reads
/// MCP servers only from its global `~/.codex/config.toml`, so its
/// wiring is the exact `codex mcp add` command printed as the next
/// action — quickstart never writes outside the target directory.
#[derive(ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
pub enum AgentTarget {
    /// Claude Code — project `.mcp.json`.
    ClaudeCode,
    /// OpenAI Codex — prints the `codex mcp add` one-liner (Codex has
    /// no project-scoped MCP config file).
    Codex,
    /// Cursor — project `.cursor/mcp.json`.
    Cursor,
    /// Gemini CLI — project `.gemini/settings.json`.
    Gemini,
}

impl AgentTarget {
    fn label(self) -> &'static str {
        match self {
            AgentTarget::ClaudeCode => "Claude Code",
            AgentTarget::Codex => "Codex",
            AgentTarget::Cursor => "Cursor",
            AgentTarget::Gemini => "Gemini CLI",
        }
    }

    /// Project-relative MCP config file, or `None` for the
    /// print-a-command target (Codex).
    fn config_file(self) -> Option<&'static str> {
        match self {
            AgentTarget::ClaudeCode => Some(".mcp.json"),
            AgentTarget::Cursor => Some(".cursor/mcp.json"),
            AgentTarget::Gemini => Some(".gemini/settings.json"),
            AgentTarget::Codex => None,
        }
    }

    const ALL: [AgentTarget; 4] = [
        AgentTarget::ClaudeCode,
        AgentTarget::Codex,
        AgentTarget::Cursor,
        AgentTarget::Gemini,
    ];
}

/// One wiring outcome per selected target, for the report.
struct WiringOutcome {
    target: AgentTarget,
    /// What happened, as a report line fragment.
    action: String,
}

pub fn run(ctx: &CliContext, args: Args) -> anyhow::Result<()> {
    let target = args
        .path
        .clone()
        .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));

    if target.exists() && !target.is_dir() {
        return Err(CliError::new(
            ExitKind::Validation,
            "INVALID_INPUT",
            format!(
                "target {} exists but is not a directory — point at a folder: \
                 memstead quickstart my-graph",
                target.display(),
            ),
        )
        .into());
    }
    if !target.exists() {
        std::fs::create_dir_all(&target).map_err(|e| {
            CliError::new(
                ExitKind::Generic,
                crate::INTERNAL_CODE,
                format!(
                    "failed to create target directory {}: {e}",
                    target.display()
                ),
            )
        })?;
    }

    // Conflict gate 1: the target itself already carries `.memstead/`.
    check_no_local_memstead(&target)?;

    // Conflict gate 2: never nest inside an existing workspace — same
    // rule and walker as `memstead init`. The alternatives named here
    // must be viable in the workspaces quickstart itself creates
    // (filesystem-shaped, no mem-lifecycle allowlist), so the message
    // points at working in the existing workspace or starting a
    // separate one — never at `memstead mem init`, which refuses on
    // both counts there.
    if let Some(found_at) = find_ancestor_workspace(&target)? {
        return Err(CliError::new(
            ExitKind::Validation,
            crate::WORKSPACE_ALREADY_EXISTS_ABOVE_CODE,
            format!(
                "{} is already inside the memstead workspace at {} — quickstart \
                 refuses to nest workspaces. Work in that workspace (memstead \
                 overview), or start a separate graph outside it: mkdir my-graph && \
                 cd my-graph && memstead quickstart",
                target.display(),
                found_at.display(),
            ),
        )
        .with_details(json!({ "found_at": found_at.display().to_string() }))
        .into());
    }

    // Conflict gate 3: tolerant emptiness. Dotfiles and non-`.md`
    // README-grade files are fine — the folder backend only reads `.md`
    // files, so they can never leak into the graph. Anything else is a
    // genuine conflict named in full; `.md` files especially, because a
    // filesystem mem owns every `.md` file in its folder and quickstart
    // must never silently adopt user content into the graph.
    let blocking = blocking_entries(&target)?;
    if !blocking.is_empty() {
        let md_note = if blocking.iter().any(|f| f.ends_with(".md`")) {
            " (a filesystem mem owns every `.md` file in its folder, so quickstart \
             would silently adopt them into the graph)"
        } else {
            ""
        };
        return Err(CliError::new(
            ExitKind::Validation,
            crate::TARGET_NOT_EMPTY_CODE,
            format!(
                "target {} has content quickstart won't touch: {}{md_note} — move it \
                 out, or start in a fresh folder: mkdir my-graph && cd my-graph && \
                 memstead quickstart",
                target.display(),
                blocking.join(", "),
            ),
        )
        .with_details(json!({
            "path": target.display().to_string(),
            "found": blocking,
        }))
        .into());
    }

    // Mem name: flag > derivation from the directory > TTY prompt >
    // refusal carrying the exact command.
    let name = resolve_mem_name(&target, args.name.as_deref())?;

    // Agent targets: flag > TTY prompt > default (Claude Code, stated).
    let (agents, agents_defaulted) = resolve_agents(&args.agents)?;

    // Preflight every selected agent's existing config file BEFORE any
    // write lands: a malformed `.mcp.json` must refuse while "re-run
    // memstead quickstart" is still true — discovering it after the
    // workspace exists would leave a half-bootstrapped directory and a
    // printed retry command that can no longer succeed.
    for agent in &agents {
        if let Some(rel) = agent.config_file() {
            read_agent_config(&target.join(rel))?;
        }
    }

    // Schema pin: the current default builtin, resolved by name so the
    // printed pin tracks the catalogue instead of a hardcoded version.
    let schema_pin = default_schema_pin()?;

    // Workspace + config through the same shared initialiser `memstead
    // init` uses — one code path, byte-identical output.
    init_filesystem_mem(&target, &name, &schema_pin).map_err(|e| {
        CliError::new(
            ExitKind::Generic,
            crate::INTERNAL_CODE,
            format!("initialise filesystem mem: {e}"),
        )
    })?;

    // Seed entity, through the engine's validated create path.
    let seed_id = seed_entity(&target, &name)?;

    // MCP wiring per selected target.
    let mcp_bin = resolve_mcp_binary();
    let mut wirings = Vec::with_capacity(agents.len());
    for agent in &agents {
        wirings.push(wire_agent(&target, *agent, &mcp_bin.command)?);
    }

    report(
        ctx,
        &target,
        &name,
        &schema_pin,
        &seed_id,
        &wirings,
        agents_defaulted,
        &mcp_bin,
    )
}

/// Refuse when the target already carries `.memstead/` — either a
/// finished workspace (point at the next command, don't re-initialise)
/// or a foreign/partial `.memstead/` directory quickstart must not
/// adopt or overwrite.
fn check_no_local_memstead(target: &Path) -> anyhow::Result<()> {
    let store = target.join(memstead_base::WORKSPACE_STORE_DIR);
    if !store.exists() {
        return Ok(());
    }
    if memstead_base::is_workspace_root(target) {
        return Err(CliError::new(
            ExitKind::Validation,
            "WORKSPACE_ALREADY_INITIALISED",
            format!(
                "{} is already a Memstead workspace — nothing to bootstrap. \
                 Inspect it with: memstead overview",
                target.display(),
            ),
        )
        .with_details(json!({ "path": target.display().to_string() }))
        .into());
    }
    Err(CliError::new(
        ExitKind::Validation,
        "FOREIGN_MEMSTEAD_DIR",
        format!(
            "{} contains a `.memstead/` directory that is not a workspace \
             (no workspace.toml) — quickstart won't adopt or overwrite it. \
             Move it aside, or start fresh: mkdir my-graph && cd my-graph && \
             memstead quickstart",
            target.display(),
        ),
    )
    .with_details(json!({ "path": store.display().to_string() }))
    .into())
}

/// Directory entries that block quickstart. Tolerated: dotfiles
/// (`.git`, `.gitignore`, `.mcp.json`, editor config, …) and non-`.md`
/// README-grade files (README, LICENSE.txt, …). Every `.md` file blocks
/// — including `README.md` — because the folder backend treats each
/// `.md` in the mem folder as an entity, and silently adopting user
/// content into the graph is the one thing quickstart must never do.
/// `.memstead` is handled earlier by [`check_no_local_memstead`].
fn blocking_entries(target: &Path) -> anyhow::Result<Vec<String>> {
    let read_err = |e: std::io::Error| {
        CliError::new(
            ExitKind::Generic,
            crate::INTERNAL_CODE,
            format!("read target {}: {e}", target.display()),
        )
    };
    let mut blocking = Vec::new();
    for entry in std::fs::read_dir(target).map_err(read_err)? {
        let entry = entry.map_err(read_err)?;
        let name = entry.file_name().to_string_lossy().to_string();
        if name.starts_with('.') {
            continue;
        }
        let lower = name.to_lowercase();
        let readme_grade = lower.starts_with("readme")
            || lower.starts_with("license")
            || lower.starts_with("licence");
        if readme_grade && !lower.ends_with(".md") {
            continue;
        }
        blocking.push(format!("`{name}`"));
    }
    blocking.sort();
    Ok(blocking)
}

/// Resolve the mem name: `--name` wins, then slug derivation from the
/// directory basename, then (TTY only) one prompt, else a refusal
/// carrying the exact retry command.
fn resolve_mem_name(target: &Path, flag: Option<&str>) -> anyhow::Result<String> {
    if let Some(name) = flag {
        validate_mem_name(name).map_err(|e| {
            CliError::new(
                ExitKind::Validation,
                "INVALID_INPUT",
                format!(
                    "invalid --name: {e}. Retry with a slug, e.g.: memstead quickstart \
                     --name {}",
                    derive_mem_name(name).unwrap_or_else(|| "my-graph".to_string()),
                ),
            )
        })?;
        return Ok(name.to_string());
    }
    let basename = std::fs::canonicalize(target)
        .ok()
        .and_then(|p| p.file_name().map(|s| s.to_string_lossy().to_string()))
        .unwrap_or_default();
    if let Some(derived) = derive_mem_name(&basename) {
        return Ok(derived);
    }
    if std::io::stdin().is_terminal() {
        let answer = prompt_line(&format!(
            "Could not derive a mem name from `{basename}`. Mem name (lowercase letters, digits, hyphens): ",
        ))?;
        let answer = answer.trim();
        validate_mem_name(answer).map_err(|e| {
            CliError::new(
                ExitKind::Validation,
                "INVALID_INPUT",
                format!("invalid mem name: {e}. Retry with: memstead quickstart --name my-graph"),
            )
        })?;
        return Ok(answer.to_string());
    }
    Err(CliError::new(
        ExitKind::Validation,
        "INVALID_INPUT",
        format!(
            "could not derive a mem name from directory `{basename}` — \
             pass one explicitly: memstead quickstart --name my-graph",
        ),
    )
    .with_details(json!({ "directory": basename }))
    .into())
}

/// Slug-derive a mem name from a directory basename: lowercase,
/// non-alphanumerics to hyphens, runs collapsed, edges trimmed, capped
/// at the 64-char rule. `None` when nothing valid survives.
fn derive_mem_name(basename: &str) -> Option<String> {
    let mut out = String::with_capacity(basename.len());
    for c in basename.to_lowercase().chars() {
        if c.is_ascii_lowercase() || c.is_ascii_digit() {
            out.push(c);
        } else if !out.is_empty() && !out.ends_with('-') {
            out.push('-');
        }
    }
    let mut slug: String = out.trim_matches('-').chars().take(64).collect();
    slug = slug.trim_matches('-').to_string();
    validate_mem_name(&slug).ok().map(|()| slug)
}

/// Resolve the agent-target list. Returns the targets plus whether the
/// non-interactive Claude Code default was applied (the report states
/// it, so a scripted run knows the choice was made for it).
fn resolve_agents(flag: &[AgentTarget]) -> anyhow::Result<(Vec<AgentTarget>, bool)> {
    if !flag.is_empty() {
        let mut seen = Vec::with_capacity(flag.len());
        for a in flag {
            if !seen.contains(a) {
                seen.push(*a);
            }
        }
        return Ok((seen, false));
    }
    if std::io::stdin().is_terminal() {
        return Ok((prompt_agents()?, false));
    }
    Ok((vec![AgentTarget::ClaudeCode], true))
}

/// The one interactive agent-target prompt. Empty answer means Claude
/// Code; otherwise comma-separated numbers from the printed list.
fn prompt_agents() -> anyhow::Result<Vec<AgentTarget>> {
    let menu: Vec<String> = AgentTarget::ALL
        .iter()
        .enumerate()
        .map(|(i, a)| format!("  {}) {}", i + 1, a.label()))
        .collect();
    let answer = prompt_line(&format!(
        "Which agents should connect to this mem? (comma-separated, Enter = Claude Code)\n{}\n> ",
        menu.join("\n"),
    ))?;
    let answer = answer.trim();
    if answer.is_empty() {
        return Ok(vec![AgentTarget::ClaudeCode]);
    }
    let mut selected = Vec::new();
    for token in answer.split(',') {
        let token = token.trim();
        let picked = match token.parse::<usize>() {
            Ok(n) if (1..=AgentTarget::ALL.len()).contains(&n) => AgentTarget::ALL[n - 1],
            _ => {
                return Err(CliError::new(
                    ExitKind::Validation,
                    "INVALID_INPUT",
                    format!(
                        "unrecognised selection `{token}` — expected numbers 1-{max} \
                         (comma-separated). Skip the prompt with: memstead quickstart \
                         --agent claude-code --agent cursor",
                        max = AgentTarget::ALL.len(),
                    ),
                )
                .into());
            }
        };
        if !selected.contains(&picked) {
            selected.push(picked);
        }
    }
    Ok(selected)
}

/// Print `msg` to stderr (stdout carries the command's report) and read
/// one line from stdin.
fn prompt_line(msg: &str) -> anyhow::Result<String> {
    let mut stderr = std::io::stderr();
    stderr.write_all(msg.as_bytes()).ok();
    stderr.flush().ok();
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).map_err(|e| {
        CliError::new(
            ExitKind::Generic,
            crate::INTERNAL_CODE,
            format!("read answer from stdin: {e}"),
        )
    })?;
    Ok(line)
}

/// Resolve the default builtin schema to its concrete pin.
fn default_schema_pin() -> anyhow::Result<memstead_schema::SchemaRef> {
    let reg = memstead_schema::SchemaRegistry::builtin();
    match reg.resolve_by_name("default") {
        Ok(Some(schema)) => {
            let (name, version) = schema.id();
            Ok(memstead_schema::SchemaRef::new(name, version))
        }
        _ => Err(CliError::new(
            ExitKind::Generic,
            crate::INTERNAL_CODE,
            "builtin schema catalogue has no `default` schema — this binary is broken, please report",
        )
        .into()),
    }
}

/// Create the seed entity through the engine's validated create path,
/// so the very first entity in the graph went through the same gate
/// every later one will.
fn seed_entity(target: &Path, mem: &str) -> anyhow::Result<String> {
    let mut engine = BaseEngine::from_workspace_root(target).map_err(|e| {
        CliError::new(
            ExitKind::Generic,
            crate::INTERNAL_CODE,
            format!("boot engine at {}: {e:#}", target.display()),
        )
    })?;
    let mut sections = indexmap::IndexMap::new();
    sections.insert(
        "definition".to_string(),
        "This mem is a typed knowledge graph: markdown entities validated against a schema, \
         connected by typed relationships."
            .to_string(),
    );
    sections.insert(
        "explanation".to_string(),
        "`memstead quickstart` seeded this entity so the graph starts non-empty. Read it back \
         with `memstead entity <id>`, list types with `memstead type`, create your own with \
         `memstead create`, and delete this one any time with `memstead delete <id>`."
            .to_string(),
    );
    let outcome = engine
        .create_entity(
            CreateEntityArgs {
                anchors: Vec::new(),
                mem: mem.to_string(),
                title: "Welcome to Memstead".to_string(),
                entity_type: "concept".to_string(),
                sections,
                metadata: indexmap::IndexMap::new(),
                relations: Vec::new(),
                dry_run: false,
            },
            Actor::Cli,
            None,
            Some("seeded by memstead quickstart"),
        )
        .map_err(CliError::from_engine_op)?;
    Ok(outcome.id.as_ref().to_string())
}

/// The resolved `memstead-mcp` launch command plus a warning when the
/// binary could not be found (the wiring is still written with the
/// bare name so a later install fixes it without re-running).
struct McpBinary {
    command: String,
    warning: Option<String>,
}

/// Resolve the `memstead-mcp` binary: sibling of the running `memstead`
/// binary first (one install ships both), then `PATH`. Falls back to
/// the bare name with a warning naming the install command.
fn resolve_mcp_binary() -> McpBinary {
    if let Ok(exe) = std::env::current_exe()
        && let Some(dir) = exe.parent()
    {
        let sibling = dir.join("memstead-mcp");
        if sibling.is_file() {
            return McpBinary {
                command: sibling.display().to_string(),
                warning: None,
            };
        }
    }
    if let Some(paths) = std::env::var_os("PATH") {
        for dir in std::env::split_paths(&paths) {
            let candidate = dir.join("memstead-mcp");
            if candidate.is_file() {
                return McpBinary {
                    command: candidate.display().to_string(),
                    warning: None,
                };
            }
        }
    }
    McpBinary {
        command: "memstead-mcp".to_string(),
        warning: Some(
            "`memstead-mcp` was not found next to this binary or on PATH — the wiring uses the \
             bare name and will work once it is installed (curl -sSf https://memstead.io/install.sh | sh)"
                .to_string(),
        ),
    }
}

/// Read and shape-check an agent's existing MCP config file: must be
/// valid JSON, a top-level object, with `mcpServers` absent or an
/// object. A missing file is an empty object. Called once as a
/// preflight before any write lands (so the refusal's "re-run
/// memstead quickstart" stays true) and again by [`wire_agent`].
fn read_agent_config(path: &Path) -> anyhow::Result<serde_json::Value> {
    if !path.is_file() {
        return Ok(json!({}));
    }
    let fix_hint = "fix or remove the file, then re-run: memstead quickstart";
    let bytes = std::fs::read(path).map_err(|e| {
        CliError::new(
            ExitKind::Generic,
            crate::INTERNAL_CODE,
            format!("read {}: {e}", path.display()),
        )
    })?;
    let root: serde_json::Value = serde_json::from_slice(&bytes).map_err(|e| {
        CliError::new(
            ExitKind::Validation,
            "INVALID_INPUT",
            format!(
                "{} exists but is not valid JSON ({e}) — {fix_hint}",
                path.display()
            ),
        )
    })?;
    if !root.is_object() {
        return Err(CliError::new(
            ExitKind::Validation,
            "INVALID_INPUT",
            format!(
                "{} exists but its top level is not a JSON object — {fix_hint}",
                path.display(),
            ),
        )
        .into());
    }
    let servers = &root["mcpServers"];
    if !servers.is_null() && !servers.is_object() {
        return Err(CliError::new(
            ExitKind::Validation,
            "INVALID_INPUT",
            format!(
                "{}'s `mcpServers` is not a JSON object — {fix_hint}",
                path.display(),
            ),
        )
        .into());
    }
    Ok(root)
}

/// Write (or merge into) the target's MCP config for one agent. JSON
/// configs get an `mcpServers.memstead` entry added, preserving every
/// existing key; an existing `memstead` entry is never overwritten.
/// Codex gets the exact `codex mcp add` command as its action line.
fn wire_agent(
    target: &Path,
    agent: AgentTarget,
    mcp_command: &str,
) -> anyhow::Result<WiringOutcome> {
    let Some(rel) = agent.config_file() else {
        return Ok(WiringOutcome {
            target: agent,
            action: format!("run: `codex mcp add memstead -- {mcp_command}`"),
        });
    };
    let path = target.join(rel);
    let mut root = read_agent_config(&path)?;

    let servers = root
        .as_object_mut()
        .expect("read_agent_config only returns JSON objects")
        .entry("mcpServers")
        .or_insert_with(|| json!({}));
    let servers = servers.as_object_mut().ok_or_else(|| {
        CliError::new(
            ExitKind::Validation,
            "INVALID_INPUT",
            format!(
                "{}'s `mcpServers` is not a JSON object — fix or remove the file, then \
                 re-run: memstead quickstart",
                path.display(),
            ),
        )
    })?;

    if servers.contains_key("memstead") {
        return Ok(WiringOutcome {
            target: agent,
            action: format!("`{rel}` already has a `memstead` server entry — left untouched"),
        });
    }
    servers.insert("memstead".to_string(), json!({ "command": mcp_command }));

    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| {
            CliError::new(
                ExitKind::Generic,
                crate::INTERNAL_CODE,
                format!("create {}: {e}", parent.display()),
            )
        })?;
    }
    let rendered = format!(
        "{}\n",
        serde_json::to_string_pretty(&root).unwrap_or_default()
    );
    std::fs::write(&path, rendered).map_err(|e| {
        CliError::new(
            ExitKind::Generic,
            crate::INTERNAL_CODE,
            format!("write {}: {e}", path.display()),
        )
    })?;
    Ok(WiringOutcome {
        target: agent,
        action: format!("wrote `{rel}` (server `memstead`)"),
    })
}

/// Final report: every artifact by name, then the single next action.
#[allow(clippy::too_many_arguments)]
fn report(
    ctx: &CliContext,
    target: &Path,
    name: &str,
    schema_pin: &memstead_schema::SchemaRef,
    seed_id: &str,
    wirings: &[WiringOutcome],
    agents_defaulted: bool,
    mcp_bin: &McpBinary,
) -> anyhow::Result<()> {
    let restart_labels: Vec<&str> = wirings.iter().map(|w| w.target.label()).collect();
    let next_action = format!(
        "Restart {} so the `memstead` MCP server registers — then try: memstead overview",
        restart_labels.join(" / "),
    );

    if ctx.json {
        return print_json(&json!({
            "workspace_root": target.display().to_string(),
            "config_path": config_path(target).display().to_string(),
            "name": name,
            "schema": schema_pin.as_display(),
            "seed_entity": seed_id,
            "mcp_command": mcp_bin.command,
            "agents": wirings
                .iter()
                .map(|w| json!({
                    "target": w.target.to_possible_value().map(|v| v.get_name().to_string()),
                    "action": w.action,
                }))
                .collect::<Vec<_>>(),
            "agents_defaulted": agents_defaulted,
            "next_action": next_action,
            "warnings": mcp_bin.warning.as_ref().map(|w| vec![w.clone()]).unwrap_or_default(),
        }));
    }

    let mut lines = vec![
        format!("# Quickstart complete — mem `{name}`"),
        String::new(),
        format!("- Workspace:   `{}`", target.display()),
        format!("- Schema pin:  `{}`", schema_pin.as_display()),
        format!("- Seed entity: `{seed_id}` (remove any time: `memstead delete {seed_id}`)"),
    ];
    for w in wirings {
        lines.push(format!("- {}: {}", w.target.label(), w.action));
    }
    if agents_defaulted {
        lines.push(
            "- No `--agent` given and no terminal to ask — defaulted to Claude Code \
             (re-run with `--agent` for others)"
                .to_string(),
        );
    }
    if let Some(warning) = &mcp_bin.warning {
        lines.push(String::new());
        lines.push(format!("> warning: {warning}"));
    }
    lines.push(String::new());
    lines.push(format!("Next: {next_action}"));
    print_markdown(&lines.join("\n"));
    Ok(())
}

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

    #[test]
    fn derive_mem_name_handles_common_directory_names() {
        assert_eq!(derive_mem_name("my-graph").as_deref(), Some("my-graph"));
        assert_eq!(derive_mem_name("My Project").as_deref(), Some("my-project"));
        assert_eq!(
            derive_mem_name("Notes_2026 (v2)").as_deref(),
            Some("notes-2026-v2")
        );
        // Nothing valid survives: prompt/refusal path.
        assert_eq!(derive_mem_name("日本語"), None);
        assert_eq!(derive_mem_name(""), None);
        // Single char fails the two-char slug rule.
        assert_eq!(derive_mem_name("a"), None);
    }

    #[test]
    fn blocking_entries_tolerates_dotfiles_and_readme_grade() {
        let tmp = tempfile::tempdir().unwrap();
        for f in [".gitignore", ".mcp.json", "README", "LICENSE", "Readme.txt"] {
            std::fs::write(tmp.path().join(f), b"x").unwrap();
        }
        std::fs::create_dir(tmp.path().join(".git")).unwrap();
        assert!(blocking_entries(tmp.path()).unwrap().is_empty());

        // A `.md` README blocks — the folder backend would adopt it as
        // an entity, and quickstart never ingests user content.
        std::fs::write(tmp.path().join("README.md"), b"# hi").unwrap();
        assert_eq!(blocking_entries(tmp.path()).unwrap(), vec!["`README.md`"]);
        std::fs::remove_file(tmp.path().join("README.md")).unwrap();

        std::fs::write(tmp.path().join("main.rs"), b"fn main() {}").unwrap();
        assert_eq!(blocking_entries(tmp.path()).unwrap(), vec!["`main.rs`"]);
    }

    #[test]
    fn wire_agent_merges_and_never_overwrites() {
        let tmp = tempfile::tempdir().unwrap();
        // Fresh write.
        let outcome = wire_agent(tmp.path(), AgentTarget::ClaudeCode, "/bin/memstead-mcp").unwrap();
        assert!(outcome.action.contains("wrote"), "got: {}", outcome.action);
        let parsed: serde_json::Value =
            serde_json::from_slice(&std::fs::read(tmp.path().join(".mcp.json")).unwrap()).unwrap();
        assert_eq!(
            parsed["mcpServers"]["memstead"]["command"],
            "/bin/memstead-mcp"
        );

        // Existing foreign server entries survive; existing `memstead`
        // entry is never overwritten.
        std::fs::write(
            tmp.path().join(".mcp.json"),
            serde_json::to_vec_pretty(&serde_json::json!({
                "mcpServers": {
                    "other": { "command": "/bin/other" },
                    "memstead": { "command": "/custom/memstead-mcp" },
                }
            }))
            .unwrap(),
        )
        .unwrap();
        let outcome = wire_agent(tmp.path(), AgentTarget::ClaudeCode, "/bin/memstead-mcp").unwrap();
        assert!(
            outcome.action.contains("left untouched"),
            "got: {}",
            outcome.action
        );
        let parsed: serde_json::Value =
            serde_json::from_slice(&std::fs::read(tmp.path().join(".mcp.json")).unwrap()).unwrap();
        assert_eq!(
            parsed["mcpServers"]["memstead"]["command"],
            "/custom/memstead-mcp"
        );
        assert_eq!(parsed["mcpServers"]["other"]["command"], "/bin/other");
    }

    #[test]
    fn wire_agent_codex_prints_command_writes_nothing() {
        let tmp = tempfile::tempdir().unwrap();
        let outcome = wire_agent(tmp.path(), AgentTarget::Codex, "/bin/memstead-mcp").unwrap();
        assert!(
            outcome
                .action
                .contains("codex mcp add memstead -- /bin/memstead-mcp"),
            "got: {}",
            outcome.action,
        );
        assert_eq!(std::fs::read_dir(tmp.path()).unwrap().count(), 0);
    }
}