Skip to main content

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    /// Declare WHO is acting in this invocation (agent-trust plan
102    /// 15): an opaque identity string of your choosing — an agent
103    /// name, a session handle, a person's tag. Recorded immutably
104    /// alongside each mutation and check (commit trailer / ledger);
105    /// the author≠checker independence gate compares identities and
106    /// nothing else. Also settable via the `MEMSTEAD_IDENTITY`
107    /// environment variable; the flag wins when both are present.
108    /// Caller-declared and unverified, but tamper-evident in
109    /// append-only history. Omit to record operations without an
110    /// identity — legal forever, never refused; identity-less
111    /// records read `unconfirmable` at the gate.
112    #[arg(long = "identity", global = true)]
113    pub identity: Option<String>,
114
115    #[command(subcommand)]
116    pub command: Command,
117}
118
119#[derive(Subcommand, Debug)]
120pub enum Command {
121    /// Node / edge counts, schema distribution, and per-binding projection state.
122    Status,
123
124    /// Read one entity as markdown.
125    Entity(commands::entity::Args),
126
127    /// List typed edges for an entity.
128    Relations(commands::relations::Args),
129
130    /// Find entities by text or graph proximity.
131    Search(commands::search::Args),
132
133    /// Filter entities by metadata (no text match — use `search` for that).
134    List(commands::list::Args),
135
136    /// Read an entity's community cluster.
137    Context(commands::context::Args),
138
139    /// All clusters with summaries and member lists. The full build
140    /// renders the same rich content the MCP `memstead_overview` tool
141    /// emits — both surfaces share the engine composer in `memstead-engine`.
142    Overview(commands::overview::Args),
143
144    /// Describe one type, or list all types when no name given.
145    Type(commands::type_cmd::Args),
146
147    /// Health summary (orphans, stubs, stale entities, missing fields).
148    Health(commands::health::Args),
149
150    /// Render the due-brief: open entities whose schema-declared due
151    /// date falls inside the window (default 90d), overdue first.
152    Due(commands::due::Args),
153
154    /// Render the gates brief: the standing of every schema-declared gated transition — closed and open entities per gate, related-check coverage, open entities in dependency order.
155    Gates(commands::gates::Args),
156
157    /// Export a mem: markdown in place, a portable `.mem` archive, JSON, one self-contained HTML page, or one agent-readable Markdown document (`llms-txt`).
158    Export(commands::export::Args),
159
160    /// Initialise a filesystem mem in the current (or named) folder.
161    /// Strict: errors out when the target is not empty.
162    Init(commands::init::InitArgs),
163
164    /// One-command cold start: workspace + default-schema mem + seed
165    /// entity + MCP wiring for your agent(s), in the current (or named)
166    /// folder. Tolerates dotfiles and README-grade files; derives the
167    /// mem name from the folder. For the strict, script-safe variant
168    /// use `memstead init`. Restart the agent session afterwards: a
169    /// session that is already running does not attach an MCP server
170    /// added while it runs.
171    Quickstart(commands::quickstart::Args),
172
173    /// Install a sealed `.mem` mem — either a local file, or `<scope>/<name>`
174    /// from the memstead.io registry. Registers it as a workspace-level
175    /// read-only mount; `memstead uninstall` is the symmetric removal.
176    /// Works on every workspace shape: a read-mem attaches to the workspace,
177    /// not to one of your mems.
178    #[cfg(feature = "mem-repo")]
179    Install(commands::install::Args),
180
181    /// Remove an installed read-mem's workspace-level mount. The global
182    /// cache copy survives by default; re-`install` re-registers it.
183    /// Works on every workspace shape, symmetric with `install`: a
184    /// workspace that can attach a read-mem can detach one.
185    #[cfg(feature = "mem-repo")]
186    Uninstall(commands::uninstall::Args),
187
188    /// Verify every anchor in a mem against its declared source — the
189    /// standalone drift statement, no binding required. Mutates no entity,
190    /// but records its findings store like any verify run.
191    #[command(name = "verify-anchors")]
192    VerifyAnchors(commands::verify_anchors::Args),
193
194    /// Publish a `.mem` archive to the registry. Triggers GitHub
195    /// Device Flow on first use; subsequent runs are silent.
196    Publish(commands::publish::Args),
197
198    /// Unpublish (hard-delete) `<scope>/<name>` from the registry.
199    /// Permitted to the original uploader and to admins. The same
200    /// `<scope>/<name>` becomes immediately re-publishable.
201    Unpublish(commands::unpublish::Args),
202
203    /// Domain-authority publishing: generate the signing key for a domain you
204    /// control and print the `.well-known` manifest to host. `publish --scope
205    /// <domain>:<handle>` then signs with that key — no GitHub account needed.
206    Domain {
207        #[command(subcommand)]
208        action: commands::domain::DomainAction,
209    },
210
211    /// Admin-only registry moderation: take a mem down or deny-list
212    /// bytes. Gated server-side by the `MEMSTEAD_ADMINS` allowlist; every
213    /// action is recorded in the registry's append-only audit log.
214    Admin {
215        #[command(subcommand)]
216        action: commands::admin::AdminAction,
217    },
218
219    /// Authenticate with a registry via GitHub Device Flow. Optional —
220    /// `publish` auto-triggers the same flow on first use.
221    Login(commands::login::Args),
222
223    /// Remove stored credentials for a registry.
224    Logout(commands::logout::Args),
225
226    /// Create a new entity. Provide `--title`, `--type`, and the required
227    /// section fields, or pass `--from <file.json>` with the full payload.
228    Create(commands::create::Args),
229
230    /// Modify an existing entity. `--expected-hash` is required for an update
231    /// that changes content, unless `--auto-hash` (refetch before write) or
232    /// `--force` (skip check) is given; an anchors-only update needs none,
233    /// since anchors sit outside the content hash.
234    Update(commands::update::Args),
235
236    /// Add or remove a typed relationship between two entities.
237    Relate(commands::relate::Args),
238
239    /// Delete an entity. Use `--dry-run` to preview impact first.
240    /// Delete is hashless by design (no post-state to race on); race
241    /// protection comes from `HAS_INCOMING_REFS` — and
242    /// `RESIDUAL_STUB_FOR_READONLY_REFERRERS` for read-only-referrer cases.
243    Delete(commands::delete::Args),
244
245    /// Rename an entity (changes ID, file path, and every incoming wiki-link).
246    Rename(commands::rename::Args),
247
248    /// Update many entities in one atomic call. Input is a JSON file
249    /// with a top-level `updates: [...]` array (one entry per entity,
250    /// each with its own hash mode and mutation fields). All-or-nothing:
251    /// if any entry fails (validation, hash mismatch, missing entity)
252    /// the whole batch is refused and NOTHING is committed — fix the
253    /// named entry and resubmit. On success the batch lands as one
254    /// commit. Mirrors `memstead update` per entry.
255    /// MEM-REPO WORKSPACES ONLY — refuses with
256    /// `UNSUPPORTED_WORKSPACE_SHAPE` on the filesystem-mem workspace
257    /// `memstead quickstart` produces; fall back to one `memstead
258    /// update` per entity there.
259    #[cfg(feature = "mem-repo")]
260    #[command(name = "batch-update")]
261    BatchUpdate(commands::batch_update::Args),
262
263    /// Create many entities in one atomic call. Input is a JSON file
264    /// with a top-level `creates: [...]` array — each entry the same
265    /// shape as `create --from`, with its own provenance `note`.
266    /// Intra-batch references resolve as real targets (cycles included
267    /// where the schema permits), so a mutually-referencing set lands
268    /// in a single pass with no stubs. All-or-nothing: any invalid
269    /// entry refuses the whole batch and names EVERY failing entry.
270    /// One commit per touched mem.
271    /// MEM-REPO WORKSPACES ONLY — refuses with
272    /// `UNSUPPORTED_WORKSPACE_SHAPE` on the filesystem-mem workspace
273    /// `memstead quickstart` produces; fall back to one `memstead
274    /// create` per entity there (losing atomicity and intra-batch
275    /// reference resolution).
276    #[cfg(feature = "mem-repo")]
277    #[command(name = "batch-create")]
278    BatchCreate(commands::batch_create::Args),
279
280    /// Apply many edge changes in one atomic call. Input is a JSON
281    /// file with a top-level `relates: [...]` array mixing additions
282    /// and removals, applied in order — each entry mirrors `relate`
283    /// (`from` / `rel_type` / `to`, optional `remove`, `description`,
284    /// per-entry `note`). All-or-nothing: any invalid entry refuses
285    /// the whole batch and names EVERY failing entry. One commit per
286    /// touched mem.
287    /// MEM-REPO WORKSPACES ONLY — refuses with
288    /// `UNSUPPORTED_WORKSPACE_SHAPE` on the filesystem-mem workspace
289    /// `memstead quickstart` produces; fall back to one `memstead
290    /// relate` per edge there.
291    #[cfg(feature = "mem-repo")]
292    #[command(name = "batch-relate")]
293    BatchRelate(commands::batch_relate::Args),
294
295    /// Apply parse-time-drift recovery across writable mems. Walks
296    /// `PARSED_RELATION_INVALID` warnings, re-renders affected
297    /// source entities to drop the stale rows, and reports per-entry
298    /// outcomes. Read-only-origin drops surface as skipped.
299    #[cfg(feature = "mem-repo")]
300    Recover(commands::recover::Args),
301
302    /// Read provenance anchors (E3a): `memstead anchors <id>` lists an
303    /// entity's anchors + composition; `memstead anchors --artifact <path>`
304    /// reverse-looks-up every entity whose anchor references that path
305    /// (the query the check-realization hook consumes).
306    Anchors(commands::anchors::Args),
307
308    /// List and resolve git merge conflicts in folder-backed mems —
309    /// the one sanctioned repair when a merge in the user's repo
310    /// writes conflict markers into entity files. `conflicts list`
311    /// shows conflicted entities; `conflicts resolve <id> --side
312    /// ours|theirs` keeps one side, validated before it lands and
313    /// committed as an attributed mutation.
314    Conflicts(commands::conflicts::Args),
315
316    /// Report a mem's changes since a cursor. The cursor is
317    /// backend-specific and is never a mutation's `write_id`: on a
318    /// git-branch mem pass a commit SHA (the `head` a prior call
319    /// returned, or the canonical empty-tree hash
320    /// `4b825dc642cb6eb9a060e54bf8d69288fbee4904` for a first sync);
321    /// on a folder mem pass an RFC3339 timestamp (the `ts` of the last
322    /// ledger entry you read, or empty for a first sync).
323    Changes(commands::changes::Args),
324
325    /// Record a check: "entity E checked, verdict ok | failed, via
326    /// method M" — an engine-recorded act carrying the session's
327    /// `--role`, never a mutation (entity markdown, hash, and mem
328    /// commits untouched). Derived check state serves via
329    /// `memstead entity <id> --provenance`.
330    Check(commands::check::Args),
331
332    /// Read and move the per-mem review mark — the engine's one
333    /// pointer per mem to the last human-approved state. `list` shows
334    /// every mem's mark and head; `set`/`clear` move it (explicit
335    /// target only); `diff` reports the unreviewed delta. Marks never
336    /// gate writes.
337    #[command(name = "review-mark")]
338    ReviewMark(commands::review_mark::Args),
339
340    /// Reload one writable mem's slice of the in-memory store from
341    /// its on-disk branch tip — or every writable mem when
342    /// `--mem` is omitted. CLI parity with the MCP `memstead_reload`
343    /// tool.
344    Reload(commands::reload::Args),
345
346    /// Fetch a mem's branch refs from a git remote into the mem-repo
347    /// (no local branch moves — inspect first, then `pull`). Requires a
348    /// git-branch-backed mem (`INVALID_INPUT` on folder mounts);
349    /// refuses `UNKNOWN_REMOTE` when the remote is not configured.
350    #[cfg(feature = "mem-repo")]
351    Fetch(commands::transport::FetchArgs),
352
353    /// Fast-forward a mem's branch to its fetched remote counterpart
354    /// and reload the in-memory store. Refuses `LOCAL_DIVERGENCE` when
355    /// the local branch is not an ancestor of the remote — reconcile
356    /// via `branch-reset`, or resolve on another clone and push.
357    #[cfg(feature = "mem-repo")]
358    Pull(commands::transport::PullArgs),
359
360    /// Push a mem's branch to a git remote. `--force` uses
361    /// force-with-lease semantics; without it, non-fast-forward pushes
362    /// refuse (`NON_FAST_FORWARD`). Refuses `UNKNOWN_REMOTE` when the
363    /// remote is not configured.
364    #[cfg(feature = "mem-repo")]
365    Push(commands::transport::PushArgs),
366
367    /// Reset a mem's branch pointer to a target ref/SHA. Refuses to
368    /// discard commits reachable from any remote ref
369    /// (`PUSHED_COMMITS_PROTECTED`).
370    #[cfg(feature = "mem-repo")]
371    #[command(name = "branch-reset")]
372    BranchReset(commands::branch_reset::BranchResetArgs),
373
374    /// Mem lifecycle commands.
375    #[cfg(feature = "mem-repo")]
376    Mem {
377        #[command(subcommand)]
378        action: commands::mem::MemAction,
379    },
380
381    /// Mem-repo-git lifecycle commands.
382    #[cfg(feature = "mem-repo")]
383    #[command(name = "mem-repo")]
384    MemRepo {
385        #[command(subcommand)]
386        action: commands::mem_repo::MemRepoAction,
387    },
388
389    /// Introspect and configure workspace policy — `dump` reads the
390    /// effective config; `allow-create`/`revoke-create`/`allow-delete`/
391    /// `revoke-delete`/`grant-cross-link`/`revoke-cross-link`/`set-mutations`
392    /// write the mem-lifecycle allowlist, cross-mem link grants, and
393    /// mutation policy.
394    #[cfg(feature = "mem-repo")]
395    Workspace {
396        #[command(subcommand)]
397        action: commands::workspace::WorkspaceAction,
398    },
399
400    /// Author-time schema tooling. `memstead schema validate <path>`
401    /// checks a schema package directory against the engine's loader
402    /// without touching a workspace.
403    Schema(commands::schema::Args),
404
405    /// Pipeline tooling — one versioned v2 binding per pipeline, sources
406    /// inline. Nine verbs: `brief` renders a binding's run-brief (the
407    /// Markdown prompt an agent consumes); `init` scaffolds a fresh v2
408    /// record non-interactively; `migrate` converts every prior on-disk
409    /// generation (gen-1 root folders, the four-primitive store, the v1
410    /// three-file store) into v2 records in place; `enable
411    /// <build|sync|verify> <binding>` adds a missing operation block;
412    /// `edit` patches a binding's author-editable fields; `advance`
413    /// records disposition-gated sync-baseline advances; `exclude`
414    /// records authored exclusions for in-scope artifacts; `verify`
415    /// measures a binding's fidelity and records findings; `check-path`
416    /// answers deny verdicts for paths and patterns.
417    Projection(commands::projection::Args),
418}
419
420impl Command {
421    /// The subcommand's user-facing verb name, as typed on the command
422    /// line — the `verb` field the friction ledger records on a typed
423    /// refusal. Nested action groups report their top-level noun
424    /// (`mem`, `mem-repo`, `workspace`, `domain`, `admin`): per-verb
425    /// counts at that granularity already answer the design questions,
426    /// and nothing payload-shaped can leak through a static name.
427    pub fn verb(&self) -> &'static str {
428        match self {
429            Command::Status => "status",
430            Command::Entity(_) => "entity",
431            Command::Relations(_) => "relations",
432            Command::Search(_) => "search",
433            Command::List(_) => "list",
434            Command::Context(_) => "context",
435            Command::Overview(_) => "overview",
436            Command::Type(_) => "type",
437            Command::Health(_) => "health",
438            Command::Due(_) => "due",
439            Command::Gates(_) => "gates",
440            Command::Export(_) => "export",
441            Command::Init(_) => "init",
442            Command::Quickstart(_) => "quickstart",
443            #[cfg(feature = "mem-repo")]
444            Command::Install(_) => "install",
445            #[cfg(feature = "mem-repo")]
446            Command::Uninstall(_) => "uninstall",
447            Command::VerifyAnchors(_) => "verify-anchors",
448            Command::Publish(_) => "publish",
449            Command::Unpublish(_) => "unpublish",
450            Command::Domain { .. } => "domain",
451            Command::Admin { .. } => "admin",
452            Command::Login(_) => "login",
453            Command::Logout(_) => "logout",
454            Command::Create(_) => "create",
455            Command::Update(_) => "update",
456            Command::Relate(_) => "relate",
457            Command::Delete(_) => "delete",
458            Command::Rename(_) => "rename",
459            #[cfg(feature = "mem-repo")]
460            Command::BatchUpdate(_) => "batch-update",
461            #[cfg(feature = "mem-repo")]
462            Command::BatchCreate(_) => "batch-create",
463            #[cfg(feature = "mem-repo")]
464            Command::BatchRelate(_) => "batch-relate",
465            #[cfg(feature = "mem-repo")]
466            Command::Recover(_) => "recover",
467            Command::Anchors(_) => "anchors",
468            Command::Conflicts(_) => "conflicts",
469            Command::Changes(_) => "changes",
470            Command::Check(_) => "check",
471            Command::ReviewMark(_) => "review-mark",
472            Command::Reload(_) => "reload",
473            #[cfg(feature = "mem-repo")]
474            Command::Fetch(_) => "fetch",
475            #[cfg(feature = "mem-repo")]
476            Command::Pull(_) => "pull",
477            #[cfg(feature = "mem-repo")]
478            Command::Push(_) => "push",
479            #[cfg(feature = "mem-repo")]
480            Command::BranchReset(_) => "branch-reset",
481            #[cfg(feature = "mem-repo")]
482            Command::Mem { .. } => "mem",
483            #[cfg(feature = "mem-repo")]
484            Command::MemRepo { .. } => "mem-repo",
485            #[cfg(feature = "mem-repo")]
486            Command::Workspace { .. } => "workspace",
487            Command::Schema(_) => "schema",
488            Command::Projection(_) => "projection",
489        }
490    }
491}
492
493#[cfg(test)]
494mod write_id_gloss_tests {
495    use clap::CommandFactory;
496
497    /// The CLI twin of `memstead-mcp`'s
498    /// `no_mutation_description_glosses_write_id_as_git_or_cursor`.
499    ///
500    /// That guard walks the five MCP tool descriptions and nothing
501    /// else, so it was blind to the clap tree — and the clap tree is
502    /// exactly where the defect survived a sweep: `changes` kept an
503    /// about-text reading "Pass `--since` = a prior `write_id` from a
504    /// mutation" while its own `--since` help said the cursor is never
505    /// a `write_id`. One help screen, the wrong instruction and its
506    /// correction, both on screen at once. A rename that only replaces
507    /// the identifier and never re-reads the sentence around it
508    /// produces precisely that, so the check belongs where the
509    /// sentences are.
510    ///
511    /// Walks every help string in the tree: each command's about and
512    /// long-about, and every argument's help and long-help.
513    #[test]
514    fn no_cli_help_text_glosses_write_id_as_git_or_cursor() {
515        // Each phrase would reintroduce one half of the defect: a git
516        // identity claim, or cursor advice.
517        // Structural, matching the MCP guard. This was a list of eight
518        // literals until 2026-08-27, which its own name already
519        // contradicted: "the `write_id` is a per-mem commit identifier"
520        // passes a list built for "per-mem git", and that is the exact
521        // evasion `ops/mod.rs` was rewritten to close. A sentence naming
522        // the token and calling it a commit must also name WHICH backend
523        // produces one; no sentence naming it may invite polling.
524        const CURSOR_INVITES: &[&str] = &[
525            "polling",
526            "poll via",
527            "since cursor",
528            "as the `since`",
529            "prior `write_id`",
530            "`write_id` from a mutation",
531        ];
532
533        fn texts(cmd: &clap::Command, path: &str, out: &mut Vec<(String, String)>) {
534            let mut push = |s: Option<&clap::builder::StyledStr>| {
535                if let Some(v) = s {
536                    out.push((path.to_string(), v.to_string()));
537                }
538            };
539            push(cmd.get_about());
540            push(cmd.get_long_about());
541            for arg in cmd.get_arguments() {
542                if let Some(h) = arg.get_help() {
543                    out.push((format!("{path} --{}", arg.get_id()), h.to_string()));
544                }
545                if let Some(h) = arg.get_long_help() {
546                    out.push((format!("{path} --{}", arg.get_id()), h.to_string()));
547                }
548            }
549            for sub in cmd.get_subcommands() {
550                if sub.get_name() == "help" {
551                    continue;
552                }
553                let child = if path.is_empty() {
554                    sub.get_name().to_string()
555                } else {
556                    format!("{path} {}", sub.get_name())
557                };
558                texts(sub, &child, out);
559            }
560        }
561
562        let cmd = super::Cli::command();
563        let mut all = Vec::new();
564        texts(&cmd, "", &mut all);
565
566        let mut violations = Vec::new();
567        for (where_, text) in &all {
568            if !text.contains("write_id") {
569                continue;
570            }
571            // Judge EACH sentence naming the token on its own. Joining
572            // them first was the flaw in the first cut: a correct
573            // sentence later in the same help text excused a wrong one
574            // earlier, so "The `write_id` is a per-mem commit
575            // identifier" passed as long as some other sentence said
576            // "git-branch". Per-sentence also keeps a legitimate gitdir
577            // mention about something else out of scope without an
578            // allowlist, and allowlists are where the next drift hides.
579            for sentence in text.split(". ").filter(|s| s.contains("write_id")) {
580                let lower = sentence.to_lowercase();
581                if (lower.contains("commit") || lower.contains("sha"))
582                    && !lower.contains("git-branch")
583                {
584                    violations.push(format!(
585                        "`memstead {where_}` help calls `write_id` a commit without naming \
586                         which backend produces one — {sentence}"
587                    ));
588                }
589                if lower.contains("gitdir") || lower.contains("include_config") {
590                    violations.push(format!(
591                        "`memstead {where_}` help points at a gitdir in a sentence about \
592                         `write_id` — the lookup errors on a backend without one"
593                    ));
594                }
595                for phrase in CURSOR_INVITES {
596                    if lower.contains(phrase) {
597                        violations.push(format!(
598                            "`memstead {where_}` help invites polling with `write_id` \
599                             (\"{phrase}\") — it is an identity, not a change cursor"
600                        ));
601                    }
602                }
603            }
604        }
605        assert!(
606            violations.is_empty(),
607            "write_id gloss violations in CLI help:\n  {}",
608            violations.join("\n  ")
609        );
610        // Guard the guard: if the token ever stops appearing in CLI
611        // help at all, the loop above passes vacuously.
612        assert!(
613            all.iter().any(|(_, t)| t.contains("write_id")),
614            "no CLI help text mentions `write_id` — this check has gone vacuous"
615        );
616
617        // Second half: the edge spelling. The loop above only inspects
618        // text that names `write_id`, so it was blind to help that
619        // documents a relation entry with the retired bare `type` —
620        // which `batch-relate`'s about-text did, describing a shape its
621        // own `deny_unknown_fields` parser refuses. A door documenting
622        // what it rejects is worse than one saying nothing.
623        const RETIRED_EDGE_SHAPES: &[&str] = &[
624            "`from` / `type` / `to`",
625            "`from`/`type`/`to`",
626            "{from, to, type}",
627            "{to, type}",
628        ];
629        let mut edge_violations = Vec::new();
630        for (where_, text) in &all {
631            for shape in RETIRED_EDGE_SHAPES {
632                if text.contains(shape) {
633                    edge_violations.push(format!(
634                        "`memstead {where_}` help documents a relation entry as {shape} — \
635                         the type is `rel_type` on every surface and the parser refuses \
636                         the retired spelling"
637                    ));
638                }
639            }
640        }
641        // Vacuity floor for THIS half. The token half above asserts the
642        // token is mentioned somewhere; nothing asserted that any help
643        // text documents a relation entry at all, so if `--relation`
644        // stopped naming a shape this check would pass in silence.
645        assert!(
646            all.iter()
647                .any(|(_, t)| t.contains("REL_TYPE:") || t.contains("rel_type")),
648            "no CLI help documents a relation entry shape — this check has gone vacuous"
649        );
650        assert!(
651            edge_violations.is_empty(),
652            "retired edge spelling in CLI help:\n  {}",
653            edge_violations.join("\n  ")
654        );
655    }
656
657    /// Third surface class: what the CLI PRINTS, as opposed to what it
658    /// documents.
659    ///
660    /// The guard above walks the clap tree, which is help text only. It
661    /// could not see `mem init`'s receipt rendering the token under the
662    /// label "Seed commit" on a folder mem — three lines above a warning
663    /// saying the same value is not a commit. The rename had replaced
664    /// the identifier in the format argument and left the label beside
665    /// it, which is this plan's recurring failure in its third costume.
666    ///
667    /// Walks the crate's own sources for a format string that labels a
668    /// write-token value with git vocabulary. Deliberately allowlist-free:
669    /// every label was made backend-neutral instead, so an exemption list
670    /// would be the first place the next drift hides.
671    #[test]
672    fn no_rendered_cli_output_labels_a_write_id_as_a_commit() {
673        fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
674            let Ok(entries) = std::fs::read_dir(dir) else {
675                return;
676            };
677            for e in entries.flatten() {
678                let p = e.path();
679                if p.is_dir() {
680                    walk(&p, out);
681                } else if p.extension().is_some_and(|x| x == "rs") {
682                    out.push(p);
683                }
684            }
685        }
686        let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
687        let mut files = Vec::new();
688        walk(&src, &mut files);
689        assert!(
690            !files.is_empty(),
691            "found no sources — check has gone vacuous"
692        );
693
694        let mut violations = Vec::new();
695        let mut saw_a_render = false;
696        for path in &files {
697            let Ok(text) = std::fs::read_to_string(path) else {
698                continue;
699            };
700            // Skip this module's own failure messages, which necessarily
701            // quote the vocabulary they forbid.
702            let text = text
703                .split_once("mod write_id_gloss_tests")
704                .map(|(before, _)| before.to_string())
705                .unwrap_or(text);
706            let lines: Vec<&str> = text.lines().collect();
707            for (i, line) in lines.iter().enumerate() {
708                let renders_token = line.contains("write_id");
709                if renders_token && (line.contains("format!") || line.contains("push_str")) {
710                    saw_a_render = true;
711                }
712                if !renders_token {
713                    continue;
714                }
715                // Widen to a small window, not just this line. A label
716                // sits on the line above its value whenever the
717                // `format!` is wrapped, and a same-line-only rule is
718                // blind to exactly the costume the defect wore here.
719                let lo = i.saturating_sub(2);
720                let hi = (i + 3).min(lines.len());
721                let window = lines[lo..hi].join(" ").to_lowercase();
722                let renders = lines[lo..hi]
723                    .iter()
724                    .any(|l| l.contains("format!") || l.contains("push_str"));
725                if (window.contains("commit") || window.contains(" sha")) && renders {
726                    violations.push(format!(
727                        "{}:{}: {}",
728                        path.file_name().unwrap_or_default().to_string_lossy(),
729                        i + 1,
730                        line.trim()
731                    ));
732                }
733            }
734        }
735        assert!(
736            saw_a_render,
737            "no CLI source renders a write token — this check has gone vacuous"
738        );
739        assert!(
740            violations.is_empty(),
741            "rendered CLI output labels a write token with git vocabulary:\n  {}",
742            violations.join("\n  ")
743        );
744    }
745}