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
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
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
//! `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, memstead_program, shell_quote};

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 — the
/// current generation (1.3.0, the required-opt-in metadata-polarity
/// generation), so fresh workspaces never start on a superseded
/// vocabulary.
fn default_schema_pin() -> anyhow::Result<memstead_schema::SchemaRef> {
    let reg = memstead_schema::SchemaRegistry::builtin();
    match reg.get("default", &semver::Version::new(1, 3, 0)) {
        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 {
        // Codex has no project config, so this command IS the wiring —
        // it must survive an mcp path containing a space exactly as the
        // verification commands must.
        let add = ShellCmd::new("codex")
            .arg("mcp")
            .arg("add")
            .arg("memstead")
            .end_of_options()
            .arg(mcp_command)
            .render();
        return Ok(WiringOutcome {
            target: agent,
            action: format!("run: `{add}`"),
        });
    };
    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`)"),
    })
}

/// One command line the receipt prints for the reader to run.
///
/// Every printed command goes through this rather than through an ad-hoc
/// `format!`, because each one needs the same three things and each was
/// independently getting one of them wrong: the program resolved to
/// something the reader can actually invoke, every argument shell-quoted,
/// and a `cd` when the command must run inside the new workspace.
///
/// The `cd` uses the `--` terminator so a directory named `-graph`
/// reaches `cd` as an operand instead of an option.
/// One word of a command line: a value to be quoted, or shell syntax
/// to emit as-is.
enum Word {
    Value(String),
    Literal(&'static str),
}

struct ShellCmd {
    /// `cd` here first. `None` runs wherever the reader is standing.
    cd: Option<String>,
    program: String,
    args: Vec<Word>,
}

impl ShellCmd {
    fn new(program: impl Into<String>) -> Self {
        ShellCmd {
            cd: None,
            program: program.into(),
            args: Vec::new(),
        }
    }

    fn arg(mut self, arg: impl Into<String>) -> Self {
        self.args.push(Word::Value(arg.into()));
        self
    }

    /// The literal `--` end-of-options separator. Distinct from
    /// [`Self::arg`] because it is syntax, not a value: quoting it
    /// would be harmless to the shell but noise to the reader, and the
    /// leading-dash rule that protects values must not fire on it.
    fn end_of_options(mut self) -> Self {
        self.args.push(Word::Literal("--"));
        self
    }

    /// Prefix a `cd` into `dir` unless the reader is already there.
    fn in_dir(mut self, dir: &Path, already_there: bool) -> Self {
        if !already_there {
            self.cd = Some(dir.display().to_string());
        }
        self
    }

    /// The runnable line. This is what both receipts print — the
    /// markdown surface only adds its own bullet and backticks.
    fn render(&self) -> String {
        let mut out = String::new();
        if let Some(dir) = &self.cd {
            out.push_str(&format!("cd -- {} && ", shell_quote(dir)));
        }
        out.push_str(&shell_quote(&self.program));
        for arg in &self.args {
            out.push(' ');
            match arg {
                Word::Value(v) => out.push_str(&shell_quote(v)),
                Word::Literal(l) => out.push_str(l),
            }
        }
        out
    }
}

/// 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();

    // Every command this receipt prints must run verbatim, from the
    // directory the caller is actually standing in, with whatever
    // characters their paths happen to contain. Each printed command is
    // therefore built as a [`ShellCmd`] rather than formatted inline —
    // three separate rounds of this receipt shipped a command that did
    // not run, each time because one `format!` had been missed.
    //
    // A verification step the reader cannot reproduce is the same
    // defect as an undisclosed shape, so this is not cosmetic.
    let absolute = target
        .canonicalize()
        .unwrap_or_else(|_| target.to_path_buf());
    let in_cwd = std::env::current_dir()
        .ok()
        .is_some_and(|cwd| cwd == absolute);
    let memstead = memstead_program();
    let overview_cmd = ShellCmd::new(&memstead)
        .arg("overview")
        .in_dir(target, in_cwd)
        .render();
    let delete_cmd = ShellCmd::new(&memstead)
        .arg("delete")
        .arg(seed_id)
        .in_dir(target, in_cwd)
        .render();
    let version_cmd = ShellCmd::new(&mcp_bin.command).arg("--version").render();

    // Codex is wired by a command the reader still has to run, so for
    // that target the restart registers nothing until they run it. Say
    // so in order rather than naming a restart that would no-op.
    let codex_pending = wirings
        .iter()
        .any(|w| w.target == AgentTarget::Codex && w.action.starts_with("run:"));
    let restart_clause = format!(
        "Restart {} so the `memstead` MCP server registers its tools",
        restart_labels.join(" / "),
    );
    let next_action = if codex_pending {
        format!(
            "Run the `codex mcp add` command above first — it is Codex's wiring, and a restart \
             registers nothing without it. Then: {restart_clause} — then try: {overview_cmd}"
        )
    } else {
        format!("{restart_clause} — then try: {overview_cmd}")
    };
    // …but an agent session that just ran onboarding cannot restart
    // itself mid-run, so the wiring it wrote must be checkable from
    // inside that session. Held as `{what, command}` pairs so the JSON
    // surface ships runnable commands and the markdown surface adds its
    // own bullet decoration — an agent should never have to strip
    // backticks off a machine field.
    let mut verify_now: Vec<(&str, String)> = Vec::new();
    // Only claim the binary answers when we actually found one. In the
    // not-found case the warning above already names the install
    // command, and printing an unrunnable check under the heading "no
    // restart needed" would be the exact defect this block exists to
    // remove.
    if mcp_bin.warning.is_none() {
        verify_now.push(("the wired binary answers", version_cmd));
    }
    verify_now.push(("the graph is already readable", overview_cmd.clone()));

    if ctx.json {
        return print_json(&json!({
            // Absolute, so a caller that passed a relative argument can
            // use these without reconstructing its own cwd.
            "workspace_root": absolute.display().to_string(),
            "config_path": config_path(&absolute).display().to_string(),
            "seed_entity_delete_command": delete_cmd,
            "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,
            "workspace_shape": crate::setup::WorkspaceShape::Filesystem.label(),
            // The agent surface gets the whole disclosure, not just the
            // label: which shape, what it cannot do, the command for
            // the other one — the same three parts the markdown block
            // carries, from the same value.
            "workspace_shape_disclosure":
                crate::setup::shape_disclosure(crate::setup::WorkspaceShape::Filesystem).to_json(),
            "next_action": next_action,
            "verify_now": verify_now
                .iter()
                .map(|(what, command)| json!({ "what": what, "command": command }))
                .collect::<Vec<_>>(),
            "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: `{delete_cmd}`)"),
    ];
    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}"));
    }
    // The shape disclosure sits between the artifact list and the next
    // action: quickstart picked one of two workspace shapes just now,
    // and this receipt is the only output the newcomer is guaranteed
    // to read before they hit the first mem-repo-only refusal.
    lines.push(String::new());
    lines.extend(crate::setup::shape_disclosure_lines(
        crate::setup::WorkspaceShape::Filesystem,
    ));
    lines.push(String::new());
    lines.push(format!("Next: {next_action}"));
    lines.push(String::new());
    lines.push("Verify from this session, no restart needed:".to_string());
    lines.extend(
        verify_now
            .iter()
            .map(|(what, command)| format!("- {what}: `{command}`")),
    );
    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 shell_quote_leaves_ordinary_paths_alone_and_quotes_the_rest() {
        assert_eq!(
            shell_quote("/usr/local/bin/memstead-mcp"),
            "/usr/local/bin/memstead-mcp"
        );
        assert_eq!(shell_quote("my-graph"), "my-graph");
        // The case that motivated this: a directory name with a space.
        assert_eq!(shell_quote("My Graph"), "'My Graph'");
        assert_eq!(
            shell_quote("/Users/a b/bin/memstead-mcp"),
            "'/Users/a b/bin/memstead-mcp'"
        );
        // Shell metacharacters are contained, not executed.
        assert_eq!(shell_quote("a;rm -rf /"), "'a;rm -rf /'");
        assert_eq!(shell_quote("$(whoami)"), "'$(whoami)'");
        // An embedded single quote closes, escapes, and reopens.
        assert_eq!(shell_quote("it's"), r"'it'\''s'");
        assert_eq!(shell_quote(""), "''");
    }

    #[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);
    }
}