memstead-cli 0.6.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
//! Clap derive for the `memstead` binary, lifted out of `main.rs` so
//! the xtask doc generator can call `Cli::command()` against the same
//! tree the binary exposes — no duplicated declarations, no drift.
//!
//! One crate, two build configs: the default (`mem-repo`) build
//! exposes the full command set including the multi-mem / mem-repo
//! lifecycle subcommands; `--no-default-features` drops those, leaving
//! the engine-agnostic surface.

use clap::{Parser, Subcommand};

use crate::commands;

/// Top-level `--help` epilog describing the exit-code posture. The
/// taxonomy is intentionally coarse — success vs failure — because
/// agents read JSON, not exit codes, and shell scripts can lift the
/// granular `code` from `--json | jq .code`.
pub const EXIT_CODES_HELP: &str = "\
Exit codes:
  0  success
  1  generic failure (catch-all for non-classified errors)
  2  usage error (clap argument-parse failure — unknown flag, bad value)
  3  not found (entity / mem / resource missing)
  4  hash mismatch (optimistic-locking failure on a mutation)
  5  validation / schema / policy refusal

  For programmatic branching, prefer `--json` over the exit code:
    memstead <subcommand> ... --json | jq -r .code
  The JSON envelope's `code` field carries the typed token
  (e.g. INVALID_TITLE, HAS_INCOMING_REFS, CROSS_MEM_LINK_NOT_ALLOWED)
  with structured recovery details under `.details`.";

/// Query and mutate Memstead knowledge graphs from the shell.
#[derive(Parser, Debug)]
// `--version` prints the full build version (engine semver plus the
// git build sha for dev builds) so two builds between releases stay
// distinguishable in the field.
#[command(name = "memstead", version = memstead_base::build_info::full_version(), about, long_about = None, after_long_help = EXIT_CODES_HELP)]
pub struct Cli {
    /// Emit JSON instead of markdown. Matches MCP `structured_content` shape.
    #[arg(long, global = true)]
    pub json: bool,

    /// Suppress engine startup logs on stderr.
    #[arg(long, global = true)]
    pub quiet: bool,

    /// Operate on the workspace at PATH instead of walking up from the
    /// current directory (like `git -C`: the process runs as if
    /// invoked from PATH, so relative path arguments resolve against
    /// it). Also settable via the `MEMSTEAD_WORKSPACE` environment
    /// variable; the flag wins when both are present. A PATH that is
    /// not an initialised workspace refuses with
    /// `WORKSPACE_NOT_INITIALISED` naming the path — it never falls
    /// back to the directory walk.
    #[arg(long, global = true, value_name = "PATH")]
    pub workspace: Option<std::path::PathBuf>,

    /// Declare the role this invocation's mutations are performed in
    /// (agent-trust plan 13): `author` | `checker` | `verifier`.
    /// Recorded immutably alongside each mutation (commit trailer /
    /// ledger). Omit to record mutations as unspecified — legal
    /// forever, never refused.
    #[arg(long = "role", global = true)]
    pub role: Option<String>,

    #[command(subcommand)]
    pub command: Command,
}

#[derive(Subcommand, Debug)]
pub enum Command {
    /// Node / edge counts, schema distribution, and per-binding projection state.
    Status,

    /// Read one entity as markdown.
    Entity(commands::entity::Args),

    /// List typed edges for an entity.
    Relations(commands::relations::Args),

    /// Find entities by text or graph proximity.
    Search(commands::search::Args),

    /// Filter entities by metadata (no text match — use `search` for that).
    List(commands::list::Args),

    /// Read an entity's community cluster.
    Context(commands::context::Args),

    /// All clusters with summaries and member lists. The full build
    /// renders the same rich content the MCP `memstead_overview` tool
    /// emits — both surfaces share the engine composer in `memstead-engine`.
    Overview(commands::overview::Args),

    /// Describe one type, or list all types when no name given.
    Type(commands::type_cmd::Args),

    /// Health summary (orphans, stubs, stale entities, missing fields).
    Health(commands::health::Args),

    /// Render the due-brief: open entities whose schema-declared due
    /// date falls inside the window (default 90d), overdue first.
    Due(commands::due::Args),

    /// Export the write mem as markdown (in place) or as a portable `.mem` archive.
    Export(commands::export::Args),

    /// Initialise a filesystem mem in the current (or named) folder.
    /// Strict: errors out when the target is not empty.
    Init(commands::init::InitArgs),

    /// One-command cold start: workspace + default-schema mem + seed
    /// entity + MCP wiring for your agent(s), in the current (or named)
    /// folder. Tolerates dotfiles and README-grade files; derives the
    /// mem name from the folder. For the strict, script-safe variant
    /// use `memstead init`.
    Quickstart(commands::quickstart::Args),

    /// Install a sealed `.mem` mem — either a local file, or `<scope>/<name>`
    /// from the memstead.io registry. Registers it as a workspace-level
    /// read-only mount; `memstead uninstall` is the symmetric removal.
    /// MEM-REPO WORKSPACES ONLY — refuses with
    /// `UNSUPPORTED_WORKSPACE_SHAPE` on the filesystem-mem workspace
    /// `memstead quickstart` produces; bootstrap with
    /// `memstead mem-repo init` instead when you intend to install mems.
    #[cfg(feature = "mem-repo")]
    Install(commands::install::Args),

    /// Remove an installed read-mem's workspace-level mount. The global
    /// cache copy survives by default; re-`install` re-registers it.
    /// MEM-REPO WORKSPACES ONLY (see `install`).
    #[cfg(feature = "mem-repo")]
    Uninstall(commands::uninstall::Args),

    /// Verify every anchor in a mem against its declared source — the
    /// standalone drift statement, no binding required. Read-only.
    #[command(name = "verify-anchors")]
    VerifyAnchors(commands::verify_anchors::Args),

    /// Link a filesystem mem to a registry-published dependency.
    /// `memstead link <scope/name>` fetches the archive into the
    /// workspace and records the dependency in the workspace config.
    Link(commands::link::LinkArgs),

    /// Publish a `.mem` archive to the registry. Triggers GitHub
    /// Device Flow on first use; subsequent runs are silent.
    Publish(commands::publish::Args),

    /// Unpublish (hard-delete) `<scope>/<name>` from the registry.
    /// Permitted to the original uploader and to admins. The same
    /// `<scope>/<name>` becomes immediately re-publishable.
    Unpublish(commands::unpublish::Args),

    /// Domain-authority publishing: generate the signing key for a domain you
    /// control and print the `.well-known` manifest to host. `publish --scope
    /// <domain>:<handle>` then signs with that key — no GitHub account needed.
    Domain {
        #[command(subcommand)]
        action: commands::domain::DomainAction,
    },

    /// Admin-only registry moderation: take a mem down or deny-list
    /// bytes. Gated server-side by the `MEMSTEAD_ADMINS` allowlist; every
    /// action is recorded in the registry's append-only audit log.
    Admin {
        #[command(subcommand)]
        action: commands::admin::AdminAction,
    },

    /// Authenticate with a registry via GitHub Device Flow. Optional —
    /// `publish` auto-triggers the same flow on first use.
    Login(commands::login::Args),

    /// Remove stored credentials for a registry.
    Logout(commands::logout::Args),

    /// Create a new entity. Provide `--title`, `--type`, and the required
    /// section fields, or pass `--from <file.json>` with the full payload.
    Create(commands::create::Args),

    /// Modify an existing entity. `--expected-hash` is required unless
    /// `--auto-hash` (refetch before write) or `--force` (skip check) is given.
    Update(commands::update::Args),

    /// Add or remove a typed relationship between two entities.
    Relate(commands::relate::Args),

    /// Delete an entity. Use `--dry-run` to preview impact first.
    /// Delete is hashless by design (no post-state to race on); race
    /// protection comes from `HAS_INCOMING_REFS` — and
    /// `RESIDUAL_STUB_FOR_READONLY_REFERRERS` for read-only-referrer cases.
    Delete(commands::delete::Args),

    /// Rename an entity (changes ID, file path, and every incoming wiki-link).
    Rename(commands::rename::Args),

    /// Update many entities in one atomic call. Input is a JSON file
    /// with a top-level `updates: [...]` array (one entry per entity,
    /// each with its own hash mode and mutation fields). All-or-nothing:
    /// if any entry fails (validation, hash mismatch, missing entity)
    /// the whole batch is refused and NOTHING is committed — fix the
    /// named entry and resubmit. On success the batch lands as one
    /// commit. Mirrors `memstead update` per entry.
    /// MEM-REPO WORKSPACES ONLY — refuses with
    /// `UNSUPPORTED_WORKSPACE_SHAPE` on the filesystem-mem workspace
    /// `memstead quickstart` produces; fall back to one `memstead
    /// update` per entity there.
    #[cfg(feature = "mem-repo")]
    #[command(name = "batch-update")]
    BatchUpdate(commands::batch_update::Args),

    /// Create many entities in one atomic call. Input is a JSON file
    /// with a top-level `creates: [...]` array — each entry the same
    /// shape as `create --from`, with its own provenance `note`.
    /// Intra-batch references resolve as real targets (cycles included
    /// where the schema permits), so a mutually-referencing set lands
    /// in a single pass with no stubs. All-or-nothing: any invalid
    /// entry refuses the whole batch and names EVERY failing entry.
    /// One commit per touched mem.
    /// MEM-REPO WORKSPACES ONLY — refuses with
    /// `UNSUPPORTED_WORKSPACE_SHAPE` on the filesystem-mem workspace
    /// `memstead quickstart` produces; fall back to one `memstead
    /// create` per entity there (losing atomicity and intra-batch
    /// reference resolution).
    #[cfg(feature = "mem-repo")]
    #[command(name = "batch-create")]
    BatchCreate(commands::batch_create::Args),

    /// Apply many edge changes in one atomic call. Input is a JSON
    /// file with a top-level `relates: [...]` array mixing additions
    /// and removals, applied in order — each entry mirrors `relate`
    /// (`from` / `type` / `to`, optional `remove`, `description`,
    /// per-entry `note`). All-or-nothing: any invalid entry refuses
    /// the whole batch and names EVERY failing entry. One commit per
    /// touched mem.
    /// MEM-REPO WORKSPACES ONLY — refuses with
    /// `UNSUPPORTED_WORKSPACE_SHAPE` on the filesystem-mem workspace
    /// `memstead quickstart` produces; fall back to one `memstead
    /// relate` per edge there.
    #[cfg(feature = "mem-repo")]
    #[command(name = "batch-relate")]
    BatchRelate(commands::batch_relate::Args),

    /// Apply parse-time-drift recovery across writable mems. Walks
    /// `PARSED_RELATION_INVALID` warnings, re-renders affected
    /// source entities to drop the stale rows, and reports per-entry
    /// outcomes. Read-only-origin drops surface as skipped.
    /// MEM-REPO WORKSPACES ONLY (see `install`).
    #[cfg(feature = "mem-repo")]
    Recover(commands::recover::Args),

    /// Read provenance anchors (E3a): `memstead anchors <id>` lists an
    /// entity's anchors + composition; `memstead anchors --artifact <path>`
    /// reverse-looks-up every entity whose anchor references that path
    /// (the query the check-realization hook consumes).
    Anchors(commands::anchors::Args),

    /// Diff a mem's HEAD against a commit SHA. Pass `--since` = a
    /// prior `commit_sha` from a mutation, or the canonical empty-tree
    /// hash `4b825dc642cb6eb9a060e54bf8d69288fbee4904` for a first sync.
    Changes(commands::changes::Args),

    /// Record a check: "entity E checked, verdict ok | failed, via
    /// method M" — an engine-recorded act carrying the session's
    /// `--role`, never a mutation (entity markdown, hash, and mem
    /// commits untouched). Derived check state serves via
    /// `memstead entity <id> --provenance`.
    Check(commands::check::Args),

    /// Read and move the per-mem review mark — the engine's one
    /// pointer per mem to the last human-approved state. `list` shows
    /// every mem's mark and head; `set`/`clear` move it (explicit
    /// target only); `diff` reports the unreviewed delta. Marks never
    /// gate writes.
    #[command(name = "review-mark")]
    ReviewMark(commands::review_mark::Args),

    /// Reload one writable mem's slice of the in-memory store from
    /// its on-disk branch tip — or every writable mem when
    /// `--mem` is omitted. CLI parity with the MCP `memstead_reload`
    /// tool.
    Reload(commands::reload::Args),

    /// Fetch a mem's branch refs from a git remote into the mem-repo
    /// (no local branch moves — inspect first, then `pull`). Requires a
    /// git-branch-backed mem (`INVALID_INPUT` on folder mounts);
    /// refuses `UNKNOWN_REMOTE` when the remote is not configured.
    #[cfg(feature = "mem-repo")]
    Fetch(commands::transport::FetchArgs),

    /// Fast-forward a mem's branch to its fetched remote counterpart
    /// and reload the in-memory store. Refuses `LOCAL_DIVERGENCE` when
    /// the local branch is not an ancestor of the remote — reconcile
    /// via `branch-reset`, or resolve on another clone and push.
    #[cfg(feature = "mem-repo")]
    Pull(commands::transport::PullArgs),

    /// Push a mem's branch to a git remote. `--force` uses
    /// force-with-lease semantics; without it, non-fast-forward pushes
    /// refuse (`NON_FAST_FORWARD`). Refuses `UNKNOWN_REMOTE` when the
    /// remote is not configured.
    #[cfg(feature = "mem-repo")]
    Push(commands::transport::PushArgs),

    /// Reset a mem's branch pointer to a target ref/SHA. Refuses to
    /// discard commits reachable from any remote ref
    /// (`PUSHED_COMMITS_PROTECTED`).
    #[cfg(feature = "mem-repo")]
    #[command(name = "branch-reset")]
    BranchReset(commands::branch_reset::BranchResetArgs),

    /// Mem lifecycle commands.
    #[cfg(feature = "mem-repo")]
    Mem {
        #[command(subcommand)]
        action: commands::mem::MemAction,
    },

    /// Mem-repo-git lifecycle commands.
    #[cfg(feature = "mem-repo")]
    #[command(name = "mem-repo")]
    MemRepo {
        #[command(subcommand)]
        action: commands::mem_repo::MemRepoAction,
    },

    /// Introspect and configure workspace policy — `dump` reads the
    /// effective config; `allow-create`/`revoke-create`/`allow-delete`/
    /// `revoke-delete`/`grant-cross-link`/`revoke-cross-link`/`set-mutations`
    /// write the mem-lifecycle allowlist, cross-mem link grants, and
    /// mutation policy.
    #[cfg(feature = "mem-repo")]
    Workspace {
        #[command(subcommand)]
        action: commands::workspace::WorkspaceAction,
    },

    /// Author-time schema tooling. `memstead schema validate <path>`
    /// checks a schema package directory against the engine's loader
    /// without touching a workspace.
    Schema(commands::schema::Args),

    /// Pipeline tooling — one versioned v2 binding per pipeline, sources
    /// inline. `memstead projection brief <binding>` renders a binding's
    /// run-brief (the Markdown prompt an agent consumes); `memstead
    /// projection init` scaffolds a fresh v2 record non-interactively;
    /// `memstead projection migrate` converts every prior on-disk generation
    /// (gen-1 root folders, the four-primitive store, the v1 three-file
    /// store) into v2 records in place; `memstead projection advance`
    /// records disposition-gated sync-baseline advances; `memstead projection
    /// enable <build|sync|verify> <binding>` adds a missing operation block.
    Projection(commands::projection::Args),
}

impl Command {
    /// The subcommand's user-facing verb name, as typed on the command
    /// line — the `verb` field the friction ledger records on a typed
    /// refusal. Nested action groups report their top-level noun
    /// (`mem`, `mem-repo`, `workspace`, `domain`, `admin`): per-verb
    /// counts at that granularity already answer the design questions,
    /// and nothing payload-shaped can leak through a static name.
    pub fn verb(&self) -> &'static str {
        match self {
            Command::Status => "status",
            Command::Entity(_) => "entity",
            Command::Relations(_) => "relations",
            Command::Search(_) => "search",
            Command::List(_) => "list",
            Command::Context(_) => "context",
            Command::Overview(_) => "overview",
            Command::Type(_) => "type",
            Command::Health(_) => "health",
            Command::Due(_) => "due",
            Command::Export(_) => "export",
            Command::Init(_) => "init",
            Command::Quickstart(_) => "quickstart",
            #[cfg(feature = "mem-repo")]
            Command::Install(_) => "install",
            #[cfg(feature = "mem-repo")]
            Command::Uninstall(_) => "uninstall",
            Command::VerifyAnchors(_) => "verify-anchors",
            Command::Link(_) => "link",
            Command::Publish(_) => "publish",
            Command::Unpublish(_) => "unpublish",
            Command::Domain { .. } => "domain",
            Command::Admin { .. } => "admin",
            Command::Login(_) => "login",
            Command::Logout(_) => "logout",
            Command::Create(_) => "create",
            Command::Update(_) => "update",
            Command::Relate(_) => "relate",
            Command::Delete(_) => "delete",
            Command::Rename(_) => "rename",
            #[cfg(feature = "mem-repo")]
            Command::BatchUpdate(_) => "batch-update",
            #[cfg(feature = "mem-repo")]
            Command::BatchCreate(_) => "batch-create",
            #[cfg(feature = "mem-repo")]
            Command::BatchRelate(_) => "batch-relate",
            #[cfg(feature = "mem-repo")]
            Command::Recover(_) => "recover",
            Command::Anchors(_) => "anchors",
            Command::Changes(_) => "changes",
            Command::Check(_) => "check",
            Command::ReviewMark(_) => "review-mark",
            Command::Reload(_) => "reload",
            #[cfg(feature = "mem-repo")]
            Command::Fetch(_) => "fetch",
            #[cfg(feature = "mem-repo")]
            Command::Pull(_) => "pull",
            #[cfg(feature = "mem-repo")]
            Command::Push(_) => "push",
            #[cfg(feature = "mem-repo")]
            Command::BranchReset(_) => "branch-reset",
            #[cfg(feature = "mem-repo")]
            Command::Mem { .. } => "mem",
            #[cfg(feature = "mem-repo")]
            Command::MemRepo { .. } => "mem-repo",
            #[cfg(feature = "mem-repo")]
            Command::Workspace { .. } => "workspace",
            Command::Schema(_) => "schema",
            Command::Projection(_) => "projection",
        }
    }
}