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