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. `--all` pushes every mounted
368 /// git-branch mem's branch plus the workspace's schema-and-config
369 /// ref, fast-forward only: silent for refs already in sync, one line
370 /// per ref moved, a refused ref named while the others still go,
371 /// non-zero exit at the end.
372 #[cfg(feature = "mem-repo")]
373 Push(commands::transport::PushArgs),
374
375 /// Reset a mem's branch pointer to a target ref/SHA. Refuses to
376 /// discard commits reachable from any remote ref
377 /// (`PUSHED_COMMITS_PROTECTED`).
378 #[cfg(feature = "mem-repo")]
379 #[command(name = "branch-reset")]
380 BranchReset(commands::branch_reset::BranchResetArgs),
381
382 /// Mem lifecycle commands.
383 #[cfg(feature = "mem-repo")]
384 Mem {
385 #[command(subcommand)]
386 action: commands::mem::MemAction,
387 },
388
389 /// Mem-repo-git lifecycle commands.
390 #[cfg(feature = "mem-repo")]
391 #[command(name = "mem-repo")]
392 MemRepo {
393 #[command(subcommand)]
394 action: commands::mem_repo::MemRepoAction,
395 },
396
397 /// Introspect and configure workspace policy — `dump` reads the
398 /// effective config; `allow-create`/`revoke-create`/`allow-delete`/
399 /// `revoke-delete`/`grant-cross-link`/`revoke-cross-link`/`set-mutations`
400 /// write the mem-lifecycle allowlist, cross-mem link grants, and
401 /// mutation policy.
402 #[cfg(feature = "mem-repo")]
403 Workspace {
404 #[command(subcommand)]
405 action: commands::workspace::WorkspaceAction,
406 },
407
408 /// Author-time schema tooling. `memstead schema validate <path>`
409 /// checks a schema package directory against the engine's loader
410 /// without touching a workspace.
411 Schema(commands::schema::Args),
412
413 /// Pipeline tooling — one versioned v2 binding per pipeline, sources
414 /// inline. Nine verbs: `brief` renders a binding's run-brief (the
415 /// Markdown prompt an agent consumes); `init` scaffolds a fresh v2
416 /// record non-interactively; `migrate` converts every prior on-disk
417 /// generation (gen-1 root folders, the four-primitive store, the v1
418 /// three-file store) into v2 records in place; `enable
419 /// <build|sync|verify> <binding>` adds a missing operation block;
420 /// `edit` patches a binding's author-editable fields; `advance`
421 /// records disposition-gated sync-baseline advances; `exclude`
422 /// records authored exclusions for in-scope artifacts; `verify`
423 /// measures a binding's fidelity and records findings; `check-path`
424 /// answers deny verdicts for paths and patterns.
425 Projection(commands::projection::Args),
426}
427
428impl Command {
429 /// The subcommand's user-facing verb name, as typed on the command
430 /// line — the `verb` field the friction ledger records on a typed
431 /// refusal. Nested action groups report their top-level noun
432 /// (`mem`, `mem-repo`, `workspace`, `domain`, `admin`): per-verb
433 /// counts at that granularity already answer the design questions,
434 /// and nothing payload-shaped can leak through a static name.
435 pub fn verb(&self) -> &'static str {
436 match self {
437 Command::Status => "status",
438 Command::Entity(_) => "entity",
439 Command::Relations(_) => "relations",
440 Command::Search(_) => "search",
441 Command::List(_) => "list",
442 Command::Context(_) => "context",
443 Command::Overview(_) => "overview",
444 Command::Type(_) => "type",
445 Command::Health(_) => "health",
446 Command::Due(_) => "due",
447 Command::Gates(_) => "gates",
448 Command::Export(_) => "export",
449 Command::Init(_) => "init",
450 Command::Quickstart(_) => "quickstart",
451 #[cfg(feature = "mem-repo")]
452 Command::Install(_) => "install",
453 #[cfg(feature = "mem-repo")]
454 Command::Uninstall(_) => "uninstall",
455 Command::VerifyAnchors(_) => "verify-anchors",
456 Command::Publish(_) => "publish",
457 Command::Unpublish(_) => "unpublish",
458 Command::Domain { .. } => "domain",
459 Command::Admin { .. } => "admin",
460 Command::Login(_) => "login",
461 Command::Logout(_) => "logout",
462 Command::Create(_) => "create",
463 Command::Update(_) => "update",
464 Command::Relate(_) => "relate",
465 Command::Delete(_) => "delete",
466 Command::Rename(_) => "rename",
467 Command::Retype(_) => "retype",
468 #[cfg(feature = "mem-repo")]
469 Command::BatchUpdate(_) => "batch-update",
470 #[cfg(feature = "mem-repo")]
471 Command::BatchCreate(_) => "batch-create",
472 #[cfg(feature = "mem-repo")]
473 Command::BatchRelate(_) => "batch-relate",
474 #[cfg(feature = "mem-repo")]
475 Command::Recover(_) => "recover",
476 Command::Anchors(_) => "anchors",
477 Command::Conflicts(_) => "conflicts",
478 Command::Changes(_) => "changes",
479 Command::Check(_) => "check",
480 Command::ReviewMark(_) => "review-mark",
481 Command::Reload(_) => "reload",
482 #[cfg(feature = "mem-repo")]
483 Command::Fetch(_) => "fetch",
484 #[cfg(feature = "mem-repo")]
485 Command::Pull(_) => "pull",
486 #[cfg(feature = "mem-repo")]
487 Command::Push(_) => "push",
488 #[cfg(feature = "mem-repo")]
489 Command::BranchReset(_) => "branch-reset",
490 #[cfg(feature = "mem-repo")]
491 Command::Mem { .. } => "mem",
492 #[cfg(feature = "mem-repo")]
493 Command::MemRepo { .. } => "mem-repo",
494 #[cfg(feature = "mem-repo")]
495 Command::Workspace { .. } => "workspace",
496 Command::Schema(_) => "schema",
497 Command::Projection(_) => "projection",
498 }
499 }
500}
501
502#[cfg(test)]
503mod write_id_gloss_tests {
504 use clap::CommandFactory;
505
506 /// The CLI twin of `memstead-mcp`'s
507 /// `no_mutation_description_glosses_write_id_as_git_or_cursor`.
508 ///
509 /// That guard walks the five MCP tool descriptions and nothing
510 /// else, so it was blind to the clap tree — and the clap tree is
511 /// exactly where the defect survived a sweep: `changes` kept an
512 /// about-text reading "Pass `--since` = a prior `write_id` from a
513 /// mutation" while its own `--since` help said the cursor is never
514 /// a `write_id`. One help screen, the wrong instruction and its
515 /// correction, both on screen at once. A rename that only replaces
516 /// the identifier and never re-reads the sentence around it
517 /// produces precisely that, so the check belongs where the
518 /// sentences are.
519 ///
520 /// Walks every help string in the tree: each command's about and
521 /// long-about, and every argument's help and long-help.
522 #[test]
523 fn no_cli_help_text_glosses_write_id_as_git_or_cursor() {
524 // Each phrase would reintroduce one half of the defect: a git
525 // identity claim, or cursor advice.
526 // Structural, matching the MCP guard. This was a list of eight
527 // literals until 2026-08-27, which its own name already
528 // contradicted: "the `write_id` is a per-mem commit identifier"
529 // passes a list built for "per-mem git", and that is the exact
530 // evasion `ops/mod.rs` was rewritten to close. A sentence naming
531 // the token and calling it a commit must also name WHICH backend
532 // produces one; no sentence naming it may invite polling.
533 const CURSOR_INVITES: &[&str] = &[
534 "polling",
535 "poll via",
536 "since cursor",
537 "as the `since`",
538 "prior `write_id`",
539 "`write_id` from a mutation",
540 ];
541
542 fn texts(cmd: &clap::Command, path: &str, out: &mut Vec<(String, String)>) {
543 let mut push = |s: Option<&clap::builder::StyledStr>| {
544 if let Some(v) = s {
545 out.push((path.to_string(), v.to_string()));
546 }
547 };
548 push(cmd.get_about());
549 push(cmd.get_long_about());
550 for arg in cmd.get_arguments() {
551 if let Some(h) = arg.get_help() {
552 out.push((format!("{path} --{}", arg.get_id()), h.to_string()));
553 }
554 if let Some(h) = arg.get_long_help() {
555 out.push((format!("{path} --{}", arg.get_id()), h.to_string()));
556 }
557 }
558 for sub in cmd.get_subcommands() {
559 if sub.get_name() == "help" {
560 continue;
561 }
562 let child = if path.is_empty() {
563 sub.get_name().to_string()
564 } else {
565 format!("{path} {}", sub.get_name())
566 };
567 texts(sub, &child, out);
568 }
569 }
570
571 let cmd = super::Cli::command();
572 let mut all = Vec::new();
573 texts(&cmd, "", &mut all);
574
575 let mut violations = Vec::new();
576 for (where_, text) in &all {
577 if !text.contains("write_id") {
578 continue;
579 }
580 // Judge EACH sentence naming the token on its own. Joining
581 // them first was the flaw in the first cut: a correct
582 // sentence later in the same help text excused a wrong one
583 // earlier, so "The `write_id` is a per-mem commit
584 // identifier" passed as long as some other sentence said
585 // "git-branch". Per-sentence also keeps a legitimate gitdir
586 // mention about something else out of scope without an
587 // allowlist, and allowlists are where the next drift hides.
588 for sentence in text.split(". ").filter(|s| s.contains("write_id")) {
589 let lower = sentence.to_lowercase();
590 if (lower.contains("commit") || lower.contains("sha"))
591 && !lower.contains("git-branch")
592 {
593 violations.push(format!(
594 "`memstead {where_}` help calls `write_id` a commit without naming \
595 which backend produces one — {sentence}"
596 ));
597 }
598 if lower.contains("gitdir") || lower.contains("include_config") {
599 violations.push(format!(
600 "`memstead {where_}` help points at a gitdir in a sentence about \
601 `write_id` — the lookup errors on a backend without one"
602 ));
603 }
604 for phrase in CURSOR_INVITES {
605 if lower.contains(phrase) {
606 violations.push(format!(
607 "`memstead {where_}` help invites polling with `write_id` \
608 (\"{phrase}\") — it is an identity, not a change cursor"
609 ));
610 }
611 }
612 }
613 }
614 assert!(
615 violations.is_empty(),
616 "write_id gloss violations in CLI help:\n {}",
617 violations.join("\n ")
618 );
619 // Guard the guard: if the token ever stops appearing in CLI
620 // help at all, the loop above passes vacuously.
621 assert!(
622 all.iter().any(|(_, t)| t.contains("write_id")),
623 "no CLI help text mentions `write_id` — this check has gone vacuous"
624 );
625
626 // Second half: the edge spelling. The loop above only inspects
627 // text that names `write_id`, so it was blind to help that
628 // documents a relation entry with the retired bare `type` —
629 // which `batch-relate`'s about-text did, describing a shape its
630 // own `deny_unknown_fields` parser refuses. A door documenting
631 // what it rejects is worse than one saying nothing.
632 const RETIRED_EDGE_SHAPES: &[&str] = &[
633 "`from` / `type` / `to`",
634 "`from`/`type`/`to`",
635 "{from, to, type}",
636 "{to, type}",
637 ];
638 let mut edge_violations = Vec::new();
639 for (where_, text) in &all {
640 for shape in RETIRED_EDGE_SHAPES {
641 if text.contains(shape) {
642 edge_violations.push(format!(
643 "`memstead {where_}` help documents a relation entry as {shape} — \
644 the type is `rel_type` on every surface and the parser refuses \
645 the retired spelling"
646 ));
647 }
648 }
649 }
650 // Vacuity floor for THIS half. The token half above asserts the
651 // token is mentioned somewhere; nothing asserted that any help
652 // text documents a relation entry at all, so if `--relation`
653 // stopped naming a shape this check would pass in silence.
654 assert!(
655 all.iter()
656 .any(|(_, t)| t.contains("REL_TYPE:") || t.contains("rel_type")),
657 "no CLI help documents a relation entry shape — this check has gone vacuous"
658 );
659 assert!(
660 edge_violations.is_empty(),
661 "retired edge spelling in CLI help:\n {}",
662 edge_violations.join("\n ")
663 );
664 }
665
666 /// Third surface class: what the CLI PRINTS, as opposed to what it
667 /// documents.
668 ///
669 /// The guard above walks the clap tree, which is help text only. It
670 /// could not see `mem init`'s receipt rendering the token under the
671 /// label "Seed commit" on a folder mem — three lines above a warning
672 /// saying the same value is not a commit. The rename had replaced
673 /// the identifier in the format argument and left the label beside
674 /// it, which is this plan's recurring failure in its third costume.
675 ///
676 /// Walks the crate's own sources for a format string that labels a
677 /// write-token value with git vocabulary. Deliberately allowlist-free:
678 /// every label was made backend-neutral instead, so an exemption list
679 /// would be the first place the next drift hides.
680 #[test]
681 fn no_rendered_cli_output_labels_a_write_id_as_a_commit() {
682 fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
683 let Ok(entries) = std::fs::read_dir(dir) else {
684 return;
685 };
686 for e in entries.flatten() {
687 let p = e.path();
688 if p.is_dir() {
689 walk(&p, out);
690 } else if p.extension().is_some_and(|x| x == "rs") {
691 out.push(p);
692 }
693 }
694 }
695 let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
696 let mut files = Vec::new();
697 walk(&src, &mut files);
698 assert!(
699 !files.is_empty(),
700 "found no sources — check has gone vacuous"
701 );
702
703 let mut violations = Vec::new();
704 let mut saw_a_render = false;
705 for path in &files {
706 let Ok(text) = std::fs::read_to_string(path) else {
707 continue;
708 };
709 // Skip this module's own failure messages, which necessarily
710 // quote the vocabulary they forbid.
711 let text = text
712 .split_once("mod write_id_gloss_tests")
713 .map(|(before, _)| before.to_string())
714 .unwrap_or(text);
715 let lines: Vec<&str> = text.lines().collect();
716 for (i, line) in lines.iter().enumerate() {
717 let renders_token = line.contains("write_id");
718 if renders_token && (line.contains("format!") || line.contains("push_str")) {
719 saw_a_render = true;
720 }
721 if !renders_token {
722 continue;
723 }
724 // Widen to a small window, not just this line. A label
725 // sits on the line above its value whenever the
726 // `format!` is wrapped, and a same-line-only rule is
727 // blind to exactly the costume the defect wore here.
728 let lo = i.saturating_sub(2);
729 let hi = (i + 3).min(lines.len());
730 let window = lines[lo..hi].join(" ").to_lowercase();
731 let renders = lines[lo..hi]
732 .iter()
733 .any(|l| l.contains("format!") || l.contains("push_str"));
734 if (window.contains("commit") || window.contains(" sha")) && renders {
735 violations.push(format!(
736 "{}:{}: {}",
737 path.file_name().unwrap_or_default().to_string_lossy(),
738 i + 1,
739 line.trim()
740 ));
741 }
742 }
743 }
744 assert!(
745 saw_a_render,
746 "no CLI source renders a write token — this check has gone vacuous"
747 );
748 assert!(
749 violations.is_empty(),
750 "rendered CLI output labels a write token with git vocabulary:\n {}",
751 violations.join("\n ")
752 );
753 }
754}