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