memstead_cli/cli.rs
1//! Clap derive for the `memstead` binary, lifted out of `main.rs` so
2//! the xtask doc generator can call `Cli::command()` against the same
3//! tree the binary exposes — no duplicated declarations, no drift.
4//!
5//! One crate, two build configs: the default (`mem-repo`) build
6//! exposes the full command set including the multi-mem / mem-repo
7//! lifecycle subcommands; `--no-default-features` drops those, leaving
8//! the engine-agnostic surface.
9
10use clap::{Parser, Subcommand};
11
12use crate::commands;
13
14/// Top-level `--help` epilog describing the exit-code posture. The
15/// taxonomy is intentionally coarse — success vs failure — because
16/// agents read JSON, not exit codes, and shell scripts can lift the
17/// granular `code` from `--json | jq .code`.
18///
19/// Code 6 breaks that success/failure symmetry on purpose: it means the
20/// measurement completed and the caller asked to be gated on what it
21/// found. A CI job needs three outcomes, not two, and it cannot get the
22/// third from a code that also means "the engine failed to boot". Keep
23/// it exclusive to explicit opt-in gate modes — the moment a run that
24/// FAILED returns 6, the distinction stops being worth anything.
25///
26/// The line is "did the measurement complete", not "was everything
27/// well". An artifact the pass could not read is a finding: it was
28/// observed and could not be adjudicated, which is an answer. An
29/// unreadable anchors sidecar is not: nothing could be observed at all,
30/// so verify refuses with `ANCHORS_SIDECAR_UNREADABLE` rather than
31/// reporting every artifact uncovered — that was a live defect, found
32/// 2026-08-21, where a corrupt file produced a red build blaming the
33/// mem.
34///
35/// This string is the source the published reference renders from
36/// (`docs-site/.../reference/cli/cli.md`, xtask-generated and
37/// drift-gated). Editing the table here and not regenerating leaves the
38/// published page asserting an exit-code space the binary no longer has.
39pub const EXIT_CODES_HELP: &str = "\
40Exit codes:
41 0 success
42 1 generic failure (catch-all for non-classified errors)
43 2 usage error (clap argument-parse failure — unknown flag, bad value)
44 3 not found (entity / mem / resource missing)
45 4 hash mismatch (optimistic-locking failure on a mutation)
46 5 validation / schema / policy refusal
47 6 findings present — the measurement COMPLETED and recorded
48 something you asked to be gated on
49 (`projection verify --fail-on-findings`). A run that could not
50 complete returns its own code above, so a CI job can tell \"the
51 mem and its source disagree\" from \"the engine could not run\".
52 An artifact the pass could not read is a finding, not an error:
53 it was observed, and not being able to adjudicate it is the
54 measurement's answer.
55
56 For programmatic branching, prefer `--json` over the exit code:
57 memstead <subcommand> ... --json | jq -r .code
58 One caveat, and it bites exactly where code 6 matters: a gate-mode run
59 that exits 6 emits TWO documents on stdout — the report, then the typed
60 error. The recipe above reads only the first and prints `null`. Read the
61 stream instead:
62 memstead ... --fail-on-findings --json | jq -s -r '.[-1].code'
63 The JSON envelope's `code` field carries the typed token
64 (e.g. INVALID_TITLE, HAS_INCOMING_REFS, CROSS_MEM_LINK_NOT_ALLOWED)
65 with structured recovery details under `.details`.";
66
67/// Query and mutate Memstead knowledge graphs from the shell.
68#[derive(Parser, Debug)]
69// `--version` prints the full build version (engine semver plus the
70// git build sha for dev builds) so two builds between releases stay
71// distinguishable in the field.
72#[command(name = "memstead", version = memstead_base::build_info::full_version(), about, long_about = None, after_long_help = EXIT_CODES_HELP)]
73pub struct Cli {
74 /// Emit JSON instead of markdown. Matches MCP `structured_content` shape.
75 #[arg(long, global = true)]
76 pub json: bool,
77
78 /// Suppress engine startup logs on stderr.
79 #[arg(long, global = true)]
80 pub quiet: bool,
81
82 /// Operate on the workspace at PATH instead of walking up from the
83 /// current directory (like `git -C`: the process runs as if
84 /// invoked from PATH, so relative path arguments resolve against
85 /// it). Also settable via the `MEMSTEAD_WORKSPACE` environment
86 /// variable; the flag wins when both are present. A PATH that is
87 /// not an initialised workspace refuses with
88 /// `WORKSPACE_NOT_INITIALISED` naming the path — it never falls
89 /// back to the directory walk.
90 #[arg(long, global = true, value_name = "PATH")]
91 pub workspace: Option<std::path::PathBuf>,
92
93 /// Declare the role this invocation's mutations are performed in
94 /// (agent-trust plan 13): `author` | `checker` | `verifier`.
95 /// Recorded immutably alongside each mutation (commit trailer /
96 /// ledger). Omit to record mutations as unspecified — legal
97 /// forever, never refused.
98 #[arg(long = "role", global = true)]
99 pub role: Option<String>,
100
101 #[command(subcommand)]
102 pub command: Command,
103}
104
105#[derive(Subcommand, Debug)]
106pub enum Command {
107 /// Node / edge counts, schema distribution, and per-binding projection state.
108 Status,
109
110 /// Read one entity as markdown.
111 Entity(commands::entity::Args),
112
113 /// List typed edges for an entity.
114 Relations(commands::relations::Args),
115
116 /// Find entities by text or graph proximity.
117 Search(commands::search::Args),
118
119 /// Filter entities by metadata (no text match — use `search` for that).
120 List(commands::list::Args),
121
122 /// Read an entity's community cluster.
123 Context(commands::context::Args),
124
125 /// All clusters with summaries and member lists. The full build
126 /// renders the same rich content the MCP `memstead_overview` tool
127 /// emits — both surfaces share the engine composer in `memstead-engine`.
128 Overview(commands::overview::Args),
129
130 /// Describe one type, or list all types when no name given.
131 Type(commands::type_cmd::Args),
132
133 /// Health summary (orphans, stubs, stale entities, missing fields).
134 Health(commands::health::Args),
135
136 /// Render the due-brief: open entities whose schema-declared due
137 /// date falls inside the window (default 90d), overdue first.
138 Due(commands::due::Args),
139
140 /// Export a mem: markdown in place, a portable `.mem` archive, JSON, one self-contained HTML page, or one agent-readable Markdown document (`llms-txt`).
141 Export(commands::export::Args),
142
143 /// Initialise a filesystem mem in the current (or named) folder.
144 /// Strict: errors out when the target is not empty.
145 Init(commands::init::InitArgs),
146
147 /// One-command cold start: workspace + default-schema mem + seed
148 /// entity + MCP wiring for your agent(s), in the current (or named)
149 /// folder. Tolerates dotfiles and README-grade files; derives the
150 /// mem name from the folder. For the strict, script-safe variant
151 /// use `memstead init`.
152 Quickstart(commands::quickstart::Args),
153
154 /// Install a sealed `.mem` mem — either a local file, or `<scope>/<name>`
155 /// from the memstead.io registry. Registers it as a workspace-level
156 /// read-only mount; `memstead uninstall` is the symmetric removal.
157 /// MEM-REPO WORKSPACES ONLY — refuses with
158 /// `UNSUPPORTED_WORKSPACE_SHAPE` on the filesystem-mem workspace
159 /// `memstead quickstart` produces; bootstrap with
160 /// `memstead mem-repo init` instead when you intend to install mems.
161 #[cfg(feature = "mem-repo")]
162 Install(commands::install::Args),
163
164 /// Remove an installed read-mem's workspace-level mount. The global
165 /// cache copy survives by default; re-`install` re-registers it.
166 /// MEM-REPO WORKSPACES ONLY (see `install`).
167 #[cfg(feature = "mem-repo")]
168 Uninstall(commands::uninstall::Args),
169
170 /// Verify every anchor in a mem against its declared source — the
171 /// standalone drift statement, no binding required. Mutates no entity,
172 /// but records its findings store like any verify run.
173 #[command(name = "verify-anchors")]
174 VerifyAnchors(commands::verify_anchors::Args),
175
176 /// Link a filesystem mem to a registry-published dependency.
177 /// `memstead link <scope/name>` fetches the archive into the
178 /// workspace and records the dependency in the workspace config.
179 Link(commands::link::LinkArgs),
180
181 /// Publish a `.mem` archive to the registry. Triggers GitHub
182 /// Device Flow on first use; subsequent runs are silent.
183 Publish(commands::publish::Args),
184
185 /// Unpublish (hard-delete) `<scope>/<name>` from the registry.
186 /// Permitted to the original uploader and to admins. The same
187 /// `<scope>/<name>` becomes immediately re-publishable.
188 Unpublish(commands::unpublish::Args),
189
190 /// Domain-authority publishing: generate the signing key for a domain you
191 /// control and print the `.well-known` manifest to host. `publish --scope
192 /// <domain>:<handle>` then signs with that key — no GitHub account needed.
193 Domain {
194 #[command(subcommand)]
195 action: commands::domain::DomainAction,
196 },
197
198 /// Admin-only registry moderation: take a mem down or deny-list
199 /// bytes. Gated server-side by the `MEMSTEAD_ADMINS` allowlist; every
200 /// action is recorded in the registry's append-only audit log.
201 Admin {
202 #[command(subcommand)]
203 action: commands::admin::AdminAction,
204 },
205
206 /// Authenticate with a registry via GitHub Device Flow. Optional —
207 /// `publish` auto-triggers the same flow on first use.
208 Login(commands::login::Args),
209
210 /// Remove stored credentials for a registry.
211 Logout(commands::logout::Args),
212
213 /// Create a new entity. Provide `--title`, `--type`, and the required
214 /// section fields, or pass `--from <file.json>` with the full payload.
215 Create(commands::create::Args),
216
217 /// Modify an existing entity. `--expected-hash` is required unless
218 /// `--auto-hash` (refetch before write) or `--force` (skip check) is given.
219 Update(commands::update::Args),
220
221 /// Add or remove a typed relationship between two entities.
222 Relate(commands::relate::Args),
223
224 /// Delete an entity. Use `--dry-run` to preview impact first.
225 /// Delete is hashless by design (no post-state to race on); race
226 /// protection comes from `HAS_INCOMING_REFS` — and
227 /// `RESIDUAL_STUB_FOR_READONLY_REFERRERS` for read-only-referrer cases.
228 Delete(commands::delete::Args),
229
230 /// Rename an entity (changes ID, file path, and every incoming wiki-link).
231 Rename(commands::rename::Args),
232
233 /// Update many entities in one atomic call. Input is a JSON file
234 /// with a top-level `updates: [...]` array (one entry per entity,
235 /// each with its own hash mode and mutation fields). All-or-nothing:
236 /// if any entry fails (validation, hash mismatch, missing entity)
237 /// the whole batch is refused and NOTHING is committed — fix the
238 /// named entry and resubmit. On success the batch lands as one
239 /// commit. Mirrors `memstead update` per entry.
240 /// MEM-REPO WORKSPACES ONLY — refuses with
241 /// `UNSUPPORTED_WORKSPACE_SHAPE` on the filesystem-mem workspace
242 /// `memstead quickstart` produces; fall back to one `memstead
243 /// update` per entity there.
244 #[cfg(feature = "mem-repo")]
245 #[command(name = "batch-update")]
246 BatchUpdate(commands::batch_update::Args),
247
248 /// Create many entities in one atomic call. Input is a JSON file
249 /// with a top-level `creates: [...]` array — each entry the same
250 /// shape as `create --from`, with its own provenance `note`.
251 /// Intra-batch references resolve as real targets (cycles included
252 /// where the schema permits), so a mutually-referencing set lands
253 /// in a single pass with no stubs. All-or-nothing: any invalid
254 /// entry refuses the whole batch and names EVERY failing entry.
255 /// One commit per touched mem.
256 /// MEM-REPO WORKSPACES ONLY — refuses with
257 /// `UNSUPPORTED_WORKSPACE_SHAPE` on the filesystem-mem workspace
258 /// `memstead quickstart` produces; fall back to one `memstead
259 /// create` per entity there (losing atomicity and intra-batch
260 /// reference resolution).
261 #[cfg(feature = "mem-repo")]
262 #[command(name = "batch-create")]
263 BatchCreate(commands::batch_create::Args),
264
265 /// Apply many edge changes in one atomic call. Input is a JSON
266 /// file with a top-level `relates: [...]` array mixing additions
267 /// and removals, applied in order — each entry mirrors `relate`
268 /// (`from` / `type` / `to`, optional `remove`, `description`,
269 /// per-entry `note`). All-or-nothing: any invalid entry refuses
270 /// the whole batch and names EVERY failing entry. One commit per
271 /// touched mem.
272 /// MEM-REPO WORKSPACES ONLY — refuses with
273 /// `UNSUPPORTED_WORKSPACE_SHAPE` on the filesystem-mem workspace
274 /// `memstead quickstart` produces; fall back to one `memstead
275 /// relate` per edge there.
276 #[cfg(feature = "mem-repo")]
277 #[command(name = "batch-relate")]
278 BatchRelate(commands::batch_relate::Args),
279
280 /// Apply parse-time-drift recovery across writable mems. Walks
281 /// `PARSED_RELATION_INVALID` warnings, re-renders affected
282 /// source entities to drop the stale rows, and reports per-entry
283 /// outcomes. Read-only-origin drops surface as skipped.
284 /// MEM-REPO WORKSPACES ONLY (see `install`).
285 #[cfg(feature = "mem-repo")]
286 Recover(commands::recover::Args),
287
288 /// Read provenance anchors (E3a): `memstead anchors <id>` lists an
289 /// entity's anchors + composition; `memstead anchors --artifact <path>`
290 /// reverse-looks-up every entity whose anchor references that path
291 /// (the query the check-realization hook consumes).
292 Anchors(commands::anchors::Args),
293
294 /// List and resolve git merge conflicts in folder-backed mems —
295 /// the one sanctioned repair when a merge in the user's repo
296 /// writes conflict markers into entity files. `conflicts list`
297 /// shows conflicted entities; `conflicts resolve <id> --side
298 /// ours|theirs` keeps one side, validated before it lands and
299 /// committed as an attributed mutation.
300 Conflicts(commands::conflicts::Args),
301
302 /// Diff a mem's HEAD against a commit SHA. Pass `--since` = a
303 /// prior `commit_sha` from a mutation, or the canonical empty-tree
304 /// hash `4b825dc642cb6eb9a060e54bf8d69288fbee4904` for a first sync.
305 Changes(commands::changes::Args),
306
307 /// Record a check: "entity E checked, verdict ok | failed, via
308 /// method M" — an engine-recorded act carrying the session's
309 /// `--role`, never a mutation (entity markdown, hash, and mem
310 /// commits untouched). Derived check state serves via
311 /// `memstead entity <id> --provenance`.
312 Check(commands::check::Args),
313
314 /// Read and move the per-mem review mark — the engine's one
315 /// pointer per mem to the last human-approved state. `list` shows
316 /// every mem's mark and head; `set`/`clear` move it (explicit
317 /// target only); `diff` reports the unreviewed delta. Marks never
318 /// gate writes.
319 #[command(name = "review-mark")]
320 ReviewMark(commands::review_mark::Args),
321
322 /// Reload one writable mem's slice of the in-memory store from
323 /// its on-disk branch tip — or every writable mem when
324 /// `--mem` is omitted. CLI parity with the MCP `memstead_reload`
325 /// tool.
326 Reload(commands::reload::Args),
327
328 /// Fetch a mem's branch refs from a git remote into the mem-repo
329 /// (no local branch moves — inspect first, then `pull`). Requires a
330 /// git-branch-backed mem (`INVALID_INPUT` on folder mounts);
331 /// refuses `UNKNOWN_REMOTE` when the remote is not configured.
332 #[cfg(feature = "mem-repo")]
333 Fetch(commands::transport::FetchArgs),
334
335 /// Fast-forward a mem's branch to its fetched remote counterpart
336 /// and reload the in-memory store. Refuses `LOCAL_DIVERGENCE` when
337 /// the local branch is not an ancestor of the remote — reconcile
338 /// via `branch-reset`, or resolve on another clone and push.
339 #[cfg(feature = "mem-repo")]
340 Pull(commands::transport::PullArgs),
341
342 /// Push a mem's branch to a git remote. `--force` uses
343 /// force-with-lease semantics; without it, non-fast-forward pushes
344 /// refuse (`NON_FAST_FORWARD`). Refuses `UNKNOWN_REMOTE` when the
345 /// remote is not configured.
346 #[cfg(feature = "mem-repo")]
347 Push(commands::transport::PushArgs),
348
349 /// Reset a mem's branch pointer to a target ref/SHA. Refuses to
350 /// discard commits reachable from any remote ref
351 /// (`PUSHED_COMMITS_PROTECTED`).
352 #[cfg(feature = "mem-repo")]
353 #[command(name = "branch-reset")]
354 BranchReset(commands::branch_reset::BranchResetArgs),
355
356 /// Mem lifecycle commands.
357 #[cfg(feature = "mem-repo")]
358 Mem {
359 #[command(subcommand)]
360 action: commands::mem::MemAction,
361 },
362
363 /// Mem-repo-git lifecycle commands.
364 #[cfg(feature = "mem-repo")]
365 #[command(name = "mem-repo")]
366 MemRepo {
367 #[command(subcommand)]
368 action: commands::mem_repo::MemRepoAction,
369 },
370
371 /// Introspect and configure workspace policy — `dump` reads the
372 /// effective config; `allow-create`/`revoke-create`/`allow-delete`/
373 /// `revoke-delete`/`grant-cross-link`/`revoke-cross-link`/`set-mutations`
374 /// write the mem-lifecycle allowlist, cross-mem link grants, and
375 /// mutation policy.
376 #[cfg(feature = "mem-repo")]
377 Workspace {
378 #[command(subcommand)]
379 action: commands::workspace::WorkspaceAction,
380 },
381
382 /// Author-time schema tooling. `memstead schema validate <path>`
383 /// checks a schema package directory against the engine's loader
384 /// without touching a workspace.
385 Schema(commands::schema::Args),
386
387 /// Pipeline tooling — one versioned v2 binding per pipeline, sources
388 /// inline. `memstead projection brief <binding>` renders a binding's
389 /// run-brief (the Markdown prompt an agent consumes); `memstead
390 /// projection init` scaffolds a fresh v2 record non-interactively;
391 /// `memstead projection migrate` converts every prior on-disk generation
392 /// (gen-1 root folders, the four-primitive store, the v1 three-file
393 /// store) into v2 records in place; `memstead projection advance`
394 /// records disposition-gated sync-baseline advances; `memstead projection
395 /// enable <build|sync|verify> <binding>` adds a missing operation block.
396 Projection(commands::projection::Args),
397}
398
399impl Command {
400 /// The subcommand's user-facing verb name, as typed on the command
401 /// line — the `verb` field the friction ledger records on a typed
402 /// refusal. Nested action groups report their top-level noun
403 /// (`mem`, `mem-repo`, `workspace`, `domain`, `admin`): per-verb
404 /// counts at that granularity already answer the design questions,
405 /// and nothing payload-shaped can leak through a static name.
406 pub fn verb(&self) -> &'static str {
407 match self {
408 Command::Status => "status",
409 Command::Entity(_) => "entity",
410 Command::Relations(_) => "relations",
411 Command::Search(_) => "search",
412 Command::List(_) => "list",
413 Command::Context(_) => "context",
414 Command::Overview(_) => "overview",
415 Command::Type(_) => "type",
416 Command::Health(_) => "health",
417 Command::Due(_) => "due",
418 Command::Export(_) => "export",
419 Command::Init(_) => "init",
420 Command::Quickstart(_) => "quickstart",
421 #[cfg(feature = "mem-repo")]
422 Command::Install(_) => "install",
423 #[cfg(feature = "mem-repo")]
424 Command::Uninstall(_) => "uninstall",
425 Command::VerifyAnchors(_) => "verify-anchors",
426 Command::Link(_) => "link",
427 Command::Publish(_) => "publish",
428 Command::Unpublish(_) => "unpublish",
429 Command::Domain { .. } => "domain",
430 Command::Admin { .. } => "admin",
431 Command::Login(_) => "login",
432 Command::Logout(_) => "logout",
433 Command::Create(_) => "create",
434 Command::Update(_) => "update",
435 Command::Relate(_) => "relate",
436 Command::Delete(_) => "delete",
437 Command::Rename(_) => "rename",
438 #[cfg(feature = "mem-repo")]
439 Command::BatchUpdate(_) => "batch-update",
440 #[cfg(feature = "mem-repo")]
441 Command::BatchCreate(_) => "batch-create",
442 #[cfg(feature = "mem-repo")]
443 Command::BatchRelate(_) => "batch-relate",
444 #[cfg(feature = "mem-repo")]
445 Command::Recover(_) => "recover",
446 Command::Anchors(_) => "anchors",
447 Command::Conflicts(_) => "conflicts",
448 Command::Changes(_) => "changes",
449 Command::Check(_) => "check",
450 Command::ReviewMark(_) => "review-mark",
451 Command::Reload(_) => "reload",
452 #[cfg(feature = "mem-repo")]
453 Command::Fetch(_) => "fetch",
454 #[cfg(feature = "mem-repo")]
455 Command::Pull(_) => "pull",
456 #[cfg(feature = "mem-repo")]
457 Command::Push(_) => "push",
458 #[cfg(feature = "mem-repo")]
459 Command::BranchReset(_) => "branch-reset",
460 #[cfg(feature = "mem-repo")]
461 Command::Mem { .. } => "mem",
462 #[cfg(feature = "mem-repo")]
463 Command::MemRepo { .. } => "mem-repo",
464 #[cfg(feature = "mem-repo")]
465 Command::Workspace { .. } => "workspace",
466 Command::Schema(_) => "schema",
467 Command::Projection(_) => "projection",
468 }
469 }
470}