lean-ctx 3.12.10

LeanCTX | OSS: the open-source runtime for the Context Gateway for AI agents. CLI, MCP server, and supported proxy integrations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
// SPDX-License-Identifier: Apache-2.0
// Auto-split from the former monolithic dispatch.rs. run() (the command
// match) stays in mod.rs; standalone helpers grouped by concern.

/// Short, friendly orientation shown when a human runs bare `lean-ctx` on a
/// terminal. It goes to stderr and the stdio server starts anyway (#1595): a
/// TTY on stdin means a human *may* be watching, never that an MCP client is
/// absent — some clients spawn the server under a PTY. One obvious next step
/// (`onboard`), not the full 150-line command reference.
pub(super) fn quickstart_text() -> String {
    format!(
        "lean-ctx {version} — Context Gateway for AI agents

With no arguments, lean-ctx speaks the MCP protocol on stdin/stdout — that is
for your AI editor, not for interactive use. It is doing that right now and
will sit there waiting for JSON-RPC; press Ctrl-C to stop it. You probably
want one of these:

  lean-ctx wrap cursor   One-command setup for Cursor (recommended)
  lean-ctx wrap claude   One-command setup for Claude Code
  lean-ctx doctor        Check that everything is wired up correctly
  lean-ctx help          Common commands (or `help all` for everything)

Docs: https://leanctx.com
",
        version = env!("CARGO_PKG_VERSION"),
    )
}

/// One-line capability summary under the `--help` title. The MCP-tool count is
/// derived from the registry (single source of truth) so it can never drift
/// from the README / feature catalog.
pub(super) fn capability_banner() -> String {
    format!(
        "{} MCP tools | Select · Control · Learn · Prove (supported paths)",
        lean_ctx_server::server::registry::tool_count()
    )
}

/// Concise, tiered help shown by default for `lean-ctx help` and `--help`.
/// Covers the ~12 commands a user actually needs day to day. The exhaustive
/// reference (every subcommand, env var, read mode) lives behind
/// `lean-ctx help all` so a newcomer is never confronted with 250 lines.
pub(super) fn print_help_concise() {
    print!("{}", concise_help_text());
}

pub(super) fn concise_help_text() -> String {
    format!(
        "lean-ctx {version} — Context Gateway for AI agents

{banner}

GETTING STARTED:
    lean-ctx wrap <agent>          One-command setup (wrap cursor / wrap claude / wrap codex)
    lean-ctx unwrap <agent>        Undo wrap, restore pre-wrap config
    lean-ctx onboard               Connect all AI tools at once (zero questions)
    lean-ctx setup                 Guided setup with full control over every option
    lean-ctx doctor                Check that everything is wired up correctly
    lean-ctx inspect               Inspect recorded context operations and evidence
    lean-ctx cockpit (also: lean-ctx dashboard)  Savings · Spend · Proof in the browser

EVERYDAY COMMANDS:
    lean-ctx -c \"command\"          Run a shell command with compressed output
    lean-ctx raw \"command\"         Same, but full uncompressed output (escape hatch)
    lean-ctx read <file>           Read a file with compression
    lean-ctx grep <pattern>        Search with compressed output
    lean-ctx gain                  Terminal summary of local context-usage estimates
    lean-ctx tools <profile>       Choose how many MCP tools your agent sees
                                   (minimal · standard · power)
    lean-ctx tools health          Token-budget & rot report (unused tools,
                                   duplicate rules, stale knowledge)

MANAGE:
    lean-ctx status                Am I connected? (quick check)
    lean-ctx update                Update to the latest version
    lean-ctx enable-gpu            Install the CUDA-enabled binary (Linux, Windows)
    lean-ctx uninstall             Remove lean-ctx cleanly

SAFETY (env vars):
    LEAN_CTX_DISABLED=1            Bypass ALL compression + prevent the shell hook from loading
    LEAN_CTX_RAW=1                 Pass output through unmodified (same as --raw)

MORE:
    lean-ctx help all              Full command reference (every subcommand)
    lean-ctx cheatsheet            Context cheat sheet for AI agents

WEBSITE: https://leanctx.com
GITHUB:  https://github.com/yvgude/lean-ctx
",
        version = env!("CARGO_PKG_VERSION"),
        banner = capability_banner(),
    )
}

/// The full command reference (`lean-ctx help all`). Split out of
/// [`print_help`] the way [`concise_help_text`] is split out of
/// [`print_help_concise`], so tests can assert what the reference advertises
/// — a removed command listed here is how #1602 reached a user.
pub(super) fn full_help_text() -> String {
    format!(
        "lean-ctx {version} — Context Gateway for AI agents

{banner}

GETTING STARTED:
    lean-ctx wrap <agent>          One-command setup (wrap cursor / wrap claude / wrap codex)
    lean-ctx unwrap <agent>        Undo wrap, restore pre-wrap config
    lean-ctx onboard               Connect all AI tools at once (zero questions)
    lean-ctx setup                 Guided setup with full control over every option
    lean-ctx doctor                Check that everything is wired up correctly
    lean-ctx cockpit (also: lean-ctx dashboard)  Savings · Spend · Proof in the browser
    (everything below is reference — run `lean-ctx help` for the short version)

USAGE:
    lean-ctx                       Start MCP server (stdio)
    lean-ctx serve                 Start MCP server (Streamable HTTP)
    lean-ctx serve --daemon        Start as background daemon (Unix Domain Socket)
    lean-ctx serve --stop          Stop the active data dir's daemon (exit 1 if none)
    lean-ctx serve --status        Show the active data dir's daemon status
    lean-ctx -t \"command\"          Track command (full output + stats, no compression)
    lean-ctx -c \"command\"          Execute with compressed output (used by AI hooks)
    lean-ctx -c --raw \"command\"    Execute without compression (full output)
    lean-ctx raw \"command\"         Raw escape hatch: full, exact output (alias: bypass)
    lean-ctx exec \"command\"        Same as -c
    lean-ctx shell                 Interactive shell with compression

COMMANDS:
    gain                           On a terminal: open the Cockpit (#savings); elsewhere the text report
    gain --terminal                Local context-usage report in the terminal (observed or estimated)
    gain --web                     Open the Savings view in the Cockpit
    gain --live                    Open the Calls (Ledger) view in the Cockpit
    gain --deep                    Full breakdown (cost + tasks + agents + heatmap combined)
    gain --graph                   30-day local context-usage chart
    gain --daily                   Bordered day-by-day table with USD
    gain --score                   Gain score breakdown (4 sub-scores + trend)
    gain --cost                    Agent cost attribution report (estimated)
    spend                          Measured provider bill (real model + billed tokens)
    spend --json                   Machine-readable measured spend
    output-savings [--json]        Local output-token estimate; evaluation claims require a declared quality gate
    value-report [--format F]      Task value report (table, markdown, or json)
    gain --tasks                   Task breakdown by category
    gain --agents                  Top agents by tool spend
    gain --by-tool [--json]        Per-tool local context breakdown (calls, tokens, USD, %)
    gain --heatmap                 Top files by observed token reduction
    gain --json                    Raw JSON export of all stats
    gain --pipeline                Per-layer pipeline stats (not collected; legacy file only)
    gain --opportunity             Find missed savings in shell history (replaces discover/ghost)
    gain --raw [--json]            Plain stats output (machine-friendly)
    gain --reset                   Clear all token savings data
    gain --model=<model>           Model for USD pricing calculations
    gain --period=<week|month|all> Period for wrapped/stats (default: all)
    gain --limit=<N>               Row limit for tables (default: 10, max: 50)
    gain --wrapped                 Shareable Wrapped card (terminal)
    gain --svg [=<path>]           Shareable Wrapped card as SVG (social/OG image)
    gain --share [=<path>]         Self-hostable Wrapped page (HTML; alias: --page)
    gain --copy                    Copy a ready-to-post share line to the clipboard
    gain --svg|--share --open      Also open the written card/page in your browser
    savings [--period day|week|month|all] [--format table|json|markdown] Local representation-change report; not comparable proof
    value [--session <id>|--all] [--json]  What lean-ctx did, recomputed from the verified chains
    statusline [--wrap \"<cmd>\"]    Claude Code status line (set up by `init --agent claude`)
    inspect [--last <N>|--task <ID>] [--json]  Why the Context Gateway delivered, changed or withheld sources; --task: one task's plan→delivery→outcome
    gateway why|list|allow-once|revoke <id>  A withheld block of a model request: why, and the human-only override
    computer run|sync-users|diag|unit On a cloud computer: the agent (enrol, meter, SSH grants), the user sync and the diagnostic menu
    run \"<task>\" [--cloud --model-access own|balance] | list|status|events|logs|stop|fetch <id>  A coding agent on a task in a fresh worktree, here or on your LeanCTX computer
    claude-mod [status|install|uninstall|code-mode]  Claude Code mod: cockpit, /leanctx, wake-not-poll; Code Mode launcher
    prompt-segment [--shell zsh|bash|fish|plain]  Shell prompt segment (set up by `init --prompt`)
    learning [status]                Local learning-efficacy evidence (export/import: retired, no effect)
    autopilot [status|explain|history|export|evidence|reset]  Personal receipt-validated learning; evidence: per-workload strategy evidence (help for options)
    codex-protected --project <DIR> [--codex <PATH>|--check]  One Codex session that reaches <DIR> only through lean-ctx
    token-report [--json]          Token + memory report (project + session + CEP)
    pack --pr                      PR Context Pack (changed files, impact, tests, artifacts)
    snapshot create|list|show|verify|restore|publish|import  Context Time Machine: git-anchored, signed snapshots; replay, resume + share
    index <status|build|build-full|watch|why <file>>  Codebase index utilities
    embeddings status              Show the ONNX Runtime used for semantic embeddings (ORT_DYLIB_PATH)
    cep                            CEP report (compression metrics, cache, modes, trends)
    verify-cache [path] [--json]   Inspect local session-cache re-read behavior
    health [path] [--json] [--gate]  Code-health report: cognitive complexity, naming, navigability score + token tax
    cockpit [--port N] [--foreground] [--no-open] [--host=H] [--base-path=/prefix] [--open=browser|none|vscode]  Open the Cockpit (also: lean-ctx dashboard; background server, default http://localhost:3333)
    cockpit stop                   Stop the background Cockpit server
    serve [--host H] [--port N]    MCP over HTTP (Streamable HTTP, local-first)
    proxy start [--port=4444] [--detach]  API proxy: compress tool_results before LLM API
    proxy status                   Show proxy statistics
    daemon start|stop|restart|status  IPC daemon management
    daemon enable|disable          Auto-start daemon on login (systemd/LaunchAgent; prints service file)
    cache [list|clear|stats]       Show/manage file read cache
    sessions [list|show|delete|cleanup]  Manage saved session snapshots — PLURAL; see 'session' for live memory (alias: session-store)
    benchmark run [path] [--json]  Run a local representation comparison on project files
    benchmark report [path]        Generate a local Markdown report
    benchmark scorecard [--json]   Local representation scorecard; not a matched-workload result
    cheatsheet                     Context-tool cheat sheet & quick reference
    onboard                        Zero-prompt golden path: connect tools + sensible defaults
    setup                          Guided setup: shell + editor + verify (full control)
    install                        Alias for setup; install --repair = non-interactive refresh
    bootstrap                      Non-interactive setup + fix (zero-config)
    status [--json]                Show setup + MCP + rules status
    init [--global]                Install shell aliases (zsh/bash/fish/PowerShell)
    init --agent <name>            Configure MCP for specific editor/agent
    read <file> [-m mode]          Read file with compression
    engine context-view ...        Versioned local Engine context transport
    engine recover ...             Exact source recovery for a prior Engine view
    engine tool-session ...        Persistent SDK Agent Tools transport
    diff <file1> <file2>           Compressed file diff
    grep <pattern> [path]          Search with compressed output
    find <pattern> [path]          Find files with compressed output
    ls [path]                      Directory listing with compression
    deps [path]                    Show project dependencies
    discover                       Find uncompressed commands in shell history
    discover --card [=<path>]      Shareable 'before lean-ctx' SVG from your history
    ghost [--json]                 Ghost Token report: find hidden token waste
    filter [list|validate|init]    Manage custom compression filters (~/.lean-ctx/filters/)
    session                        Live session memory — SINGULAR; see 'sessions' to manage snapshots
    session task <desc>            Set current task
    session finding <summary>      Record a finding
    session save                   Save current session
    session load [id]              Load session (latest if no ID)
    knowledge remember <value> --category <c> --key <k>   Store a fact
    knowledge recall [query] [--category <c>]             Retrieve facts
    knowledge search <query>       Cross-project knowledge search
    knowledge export [--format json|jsonl|simple] [--output <path>]  Export knowledge
    knowledge import <path> [--merge replace|append|skip-existing]   Import knowledge
    knowledge remove --category <c> --key <k>             Remove a fact
    knowledge status               Knowledge base summary
    tasks [list|show|propose|decide|claim|update|submit|release|verify|stop] [--json]  The project's tasks (local, or its cloud vault)
    docs list|show|history|write|move|delete [--json]  The project's doc pages (local, or its cloud vault)
    activity list --json [--session <id>] [--project-root <p>] [--since <ts>] [--kind <k>]  Per-session activity stream
    agents [--json]                Coding agents on this machine (version, sign-in, LeanCTX attachment, ACP)
    bus list|read|post|leases|claim|release|revision --json  The local agent bus (agent-bus/1)
    presence list --json [--all] [--all-projects]  Local agents on the bus with liveness
    capabilities --json            Local Read kinds and verbs this Instance supports
    archive show <id> --json       One archived tool result of this project (archive.entry)
    overview [task]                Project overview (task-contextualized if given)
    explore <query> [--citation] [--depth=N]  Iterative code exploration → file:line citations
    compress [--signatures]        Context compression checkpoint
    compress diff <file|-> [--shell \"cmd\"] [--json]  Preview compression: original vs emitted + token diff
    config                         Show/edit configuration (~/.lean-ctx/config.toml)
    security [status]              Show security posture (containment + secret defense)
    yolo                           Disable containment: any path + any command (keeps secret redaction on)
    secure                         Restore secure defaults (path jail + shell gating + secret redaction)
    security secrets <on|off>      Toggle secret/.env redaction (separate from containment)
    allow <cmd>                    Allow one shell command (additive; granular re-enable after yolo)
    allow-path <dir>               Let tools reach a dir outside ~ or a protected one (no restart)
    workspace <create|add|remove|show|diagnose>  Launcher-bound Workspace: the only roots a server bound
                                   with LEAN_CTX_WORKSPACE_FILE may reach (revision-checked changes)
    tools [minimal|standard|power|show|list]  How many MCP tools your agent sees
    profile [list|show|diff|create|set|suggest]  Manage local context configuration profiles
    kit [list|load|show|unload] [name]  Manage available local TOML/.ctxpkg substrate; first-class Kit semantics are Research
    theme [list|set|export|import] Customize terminal colors and themes
    tee [list|clear|show <file>|last] Manage output tee files (~/.lean-ctx/tee/)
    compression [off|lite|standard|max]  Set local output-density preference (alias: terse)
    slow-log [list|clear]          Show/clear slow command log (~/.lean-ctx/slow-commands.log)
    debug-log [list|tail N|clear|path]  Opt-in tool-call + hook-routing log (set debug_log / LEAN_CTX_DEBUG_LOG)
    update [<version>] [--check]   Update from a verified GitHub release
                                   [--pin <version>|--unpin|--status|--rollback]
    enable-gpu [--check]           Install CUDA-enabled binary (x86_64 Linux/Windows)
    stop                           Stop ALL lean-ctx processes (daemon, proxy, orphans)
    restart                        Restart daemon (applies config.toml changes)
    dev-install [--fast|--release] Fast incremental build + atomic install + restart
    codesign-setup                 macOS: one-time stable signing identity (stops repeating TCC prompt, #356)
    gotchas [list|clear|export|stats] Bug Memory: view/manage auto-detected error patterns
    doctor integrations [--json]   Integration health checks (Cursor/Claude Code/CodeBuddy)
    doctor [--fix] [--json]        Run diagnostics (and optionally repair)
    doctor --migrate-check         v1.0 migration readiness audit (config, deprecations, data)
    migrate config [path] --rollback          Restore digest-bound pre-v4 global config
    migrate task-receipt <dir> [--rollback] Preserve or roll back V3 task migration metadata
    migrate legacy-context [--adopt --project <root> --items <ids|all> [--dry-run]]
                                   List / adopt pre-3.11.5 context that belongs to no project
    smells [scan|summary|rules|file] [--rule=<r>] [--path=<p>] [--json]
                                   Code smell detection (Property Graph, 8 rules)
    control <action> [--target=<t>] Context field manipulation (exclude/pin/priority)
    plan <task> [--budget=N]       Context planning (optimal Phi-scored context plan)
    compile [--mode=<m>] [--budget=N] Context compilation (knapsack + Boltzmann)
    addon list|search|info|add|remove
                                   Unavailable: marketplace/addon surface is Research
    decisions list|show|check|new  Recorded team decisions (.leanctx/decisions); check exits 1
                                   on a violation (--rev A..B | --staged | --diff FILE|-)
    rules sync|diff|lint|status|init
                                   Local rules management; no public cross-agent governance product
    policy list|show|validate|coverage|org  Local policy-pack utilities; organization controls are Research
    uninstall [--keep-config] [--keep-binary] [--dry-run]
                                   Full clean removal: stops all processes, removes hooks,
                                   MCP configs, rules, autostart, data, AND the binary itself.
                                   --keep-config preserves MCP/rules · --keep-binary keeps the
                                   binary · --dry-run previews without changing anything

PROJECT & AGENT TOOLS:
    semantic-search <query> [options]  Hybrid BM25 + embeddings code search (alias: search-code)
    repomap [--json] [--max-tokens N] [--limit N]  PageRank-ranked repository map (alias: repo-map)
    glob <pattern> [path]          Find files by glob pattern
    heatmap [--top=N] [--dir=D] [--by=connections|tokens] [--json]  Most-connected / costliest files
    hotspots [--limit N] [--project-root P] [--json]  Churn × merge changes × reverts × size, with a refactor plan
    call <tool> --project-root <path> --json '<json>' [--json-file <path>]
                                   Invoke one MCP tool from the shell
    ledger <status|reset|evict|prune|push> [args]  Inspect and manage the context ledger
    ocla [ocla]                    Inspect Open Context & Token Lifecycle Architecture state
    summary [recall|record|list] [query] [--top-k N]  Record + recall AI session summaries
    checkpoints [--session <id>] [--commit <sha>] [--orphaned]  List provenance checkpoints
    import <claude-code|codex|cursor|opencode>|--all [--dry-run]  Import facts from AI session histories
    skillify [mine|list|status|promote <slug>]  Codify recurring session patterns into .cursor/rules
    learn [--apply] [--mine [dir]] Learned error→fix corrections (--mine: distill a transcript dir)
    export-rules [--format mdc|agents-md|claude-md|codebuddy-md] [--root DIR]
                                   Export high-confidence knowledge as agent rules
    compact [path]                 Compact agent transcripts (default: ~/.claude/projects)
    agent register|list|presence|show|heartbeat|suspend|resume|decommission|check
                                   Agent identities: registered, attested, revocable
    client fs-read|fs-write|exec --json --session <id> --agent <id>
                                   ACP client calls through the Instance (jail, allowlist, receipts)
    instructions --client <id> [--profile <name>] [--json] | --list-clients
                                   Print the agent instructions lean-ctx generates for a client
    provider init|auth|logout|list|check|credentials
                                   Context sources (scaffolds, Jira OAuth, checks, stored credentials)
    trust [<path>|status [<path>]|--list]  Trust a workspace (gates project-level overrides)
    untrust [<path>]               Remove a workspace from the trust store
    harden [options]               Deny native Read/Grep/Glob in IDE configs
  telemetry [status|on|off|show|reset-id|history]  Inspect and control product telemetry
{cloud}    completions <zsh|bash|fish>    Print the shell completion script
    report-issue [--title T] [--description D] [--dry-run] [--include-tee]
                                   Open a GitHub issue with diagnostics (alias: report)
                                   --include-tee attaches the saved full output of your latest
                                   command; it can contain file contents and paths. Secrets are
                                   redacted, but review it (--dry-run saves the report) first
    report sign|verify --json      Sign the savings report digest, or verify a signed report
                                   Plan, entitlement and usage details

EVIDENCE & MEASUREMENT:
    stats [json|reset-cep]         Raw token counters (JSON export, reset CEP stats)
    roi [--json|--md] [--export <path>]  Recorded savings (ROI) report from the signed ledger
    finops export [--target=focus|cbf|vantage] [--from=D] [--to=D] [--out=FILE]
                                   Daily cost/savings rows from the savings ledger
    evidence run|workflow|realworld|report|v2|inspect  Generate or inspect evidence bundles
    evidence-export [--output DIR] [--format markdown|json]  Portable package of local evidence
    shadow [--latest|--list|--force]  Inspect local Shadow Mode comparisons
    verify [--format summary|json|both] [--json]  Output-verification statistics
    verify <bundle.zip> [--public-key F] [--verbose] [--json]  Verify an evidence bundle offline
    proof [--format json|summary|both] [--no-write] [--filename F]  Write context proof artifacts
    audit [evidence|determinism]   Compliance report (default), evidence audit, determinism check
    compliance report|facts|verify  Signed CISO report (frameworks: Enterprise), assessed facts, offline verify
    conformance [--json]           Conformance scorecard, non-zero exit on failure (alias: selftest)
    scenario [all|triage|knowledge|shadow|value-gate|full-loop]  Run an end-to-end scenario
    triage accuracy [--json]       Triage model accuracy report
    model install triage | model status | model remove triage  Manage the local triage model
    introspect [cognition] [--json]  Cognition snapshot (which subsystems are wired/active)
    safety-levels                  Per-command compression safety levels (alias: safety)

INTEGRATION ENTRY POINTS (called by editors and hooks, not by hand):
    mcp                            Start the MCP server on stdio (same as bare lean-ctx)
    hook <rewrite|redirect|deny|read-dedup|observe|post-commit|copilot|...>
                                   Agent hook handlers (Claude, Cursor, Copilot, Codex, Vibe)
    editor-signal --file <path>    Report the file an editor has open
    editor-session --event <open|heartbeat|close> --source <editor> --workspace <path> --session-id <id>
                                   Record editor session presence
    editor-bridge dir              Print the directory an editor's semantic bridge announces itself in
    git-trailer <msg-file> [source]  Add the lean-ctx commit trailer (prepare-commit-msg hook)

RESEARCH & RENAMED:
    upgrade [args]                 Renamed to `update`; forwards its arguments

SHELL HOOK PATTERNS (95+):
    git       status, log, diff, add, commit, push, pull, fetch, clone,
              branch, checkout, switch, merge, stash, tag, reset, remote
    docker    build, ps, images, logs, compose, exec, network
    npm/pnpm  install, test, run, list, outdated, audit
    cargo     build, test, check, clippy
    gh        pr list/view/create, issue list/view, run list/view
    kubectl   get pods/services/deployments, logs, describe, apply
    python    pip install/list/outdated, ruff check/format, poetry, uv
    linters   eslint, biome, prettier, golangci-lint
    builds    tsc, next build, vite build
    ruby      rubocop, bundle install/update, rake test, rails test
    tests     jest, vitest, pytest, go test, playwright, rspec, minitest
    iac       terraform, make, maven, gradle, dotnet, flutter, dart
    data-eng  dbt, spark, alembic, flyway
    ai        ollama, mlflow
    security  semgrep, trivy, grype, syft, cosign, swiftlint
    vcs/tool  jj, mise, buf, gem, uv add/lock/tool
    edge/iac  pulumi, linkerd, argocd, vercel, fly, wrangler, skaffold, supabase
    utils     curl, grep/rg, find, ls, wget, env
    data      JSON schema extraction, log deduplication

READ MODES:
    auto                           Auto-select optimal mode (default)
    full                           Full content (eligible re-reads use cache references)
    map                            Dependency graph + API signatures
    signatures                     tree-sitter AST extraction (27 languages)
    task                           Task-relevant filtering (requires ctx_session task)
    reference                      One-line reference stub (cheap cache key)
    aggressive                     Syntax-stripped content
    entropy                        Shannon entropy filtered
    diff                           Changed lines only
    lines:N-M                      Specific line ranges (e.g. lines:10-50,80)

ENVIRONMENT:
    LEAN_CTX_DISABLED=1            Bypass ALL compression + prevent shell hook from loading
    LEAN_CTX_ENABLED=0             Prevent shell hook auto-start (lean-ctx-on still works)
    LEAN_CTX_RAW=1                 Same as --raw for current command
    LEAN_CTX_AUTONOMY=false        Disable autonomous features
    LEAN_CTX_COMPRESS=1            Force compression (even for excluded commands)

OPTIONS:
    --version, -V                  Show version
    --help, -h                     Show this help

EXAMPLES:
    lean-ctx -c \"git status\"       Compressed git output
    lean-ctx -c \"kubectl get pods\" Compressed k8s output
    lean-ctx -c \"gh pr list\"       Compressed GitHub CLI output
    lean-ctx gain                  Open the Cockpit (#savings); --terminal for the text summary
    lean-ctx gain --live           Calls (Ledger) view in the Cockpit
    lean-ctx gain --graph          30-day local context-usage chart
    lean-ctx gain --daily          Day-by-day breakdown with USD
    lean-ctx token-report --json   Machine-readable token + memory report
    lean-ctx cockpit (also: lean-ctx dashboard)  Open the Cockpit
    lean-ctx cockpit --foreground  Run the Cockpit server in this terminal
    lean-ctx cockpit stop          Stop the background Cockpit server
    lean-ctx cockpit --host=0.0.0.0  Bind to all interfaces (remote access)
    lean-ctx gain --wrapped        Wrapped report card (recommended)
    lean-ctx gain --wrapped --period=month  Monthly Wrapped report card
    lean-ctx gain --svg            Shareable SVG card -> lean-ctx-wrapped.svg
    lean-ctx gain --svg=card.svg --period=month  Monthly SVG card to a chosen path
    lean-ctx gain --share          Self-hostable Wrapped page -> lean-ctx-wrapped.html
    lean-ctx gain --share --base-url=https://you.dev/w  Page with social preview meta
    lean-ctx gain --copy           Copy your share line to the clipboard
    lean-ctx savings               Local representation-change ledger; not comparable proof by itself
    lean-ctx savings verify        Re-check the savings ledger SHA-256 hash chain
    lean-ctx savings sign          Export an Ed25519-signed savings batch (ROI/audit artifact)
    lean-ctx savings verify-batch <file>  Verify a signed batch offline (no ledger needed)
    lean-ctx sessions list         List all CCP sessions
    lean-ctx sessions show         Show latest session state
    lean-ctx sessions delete <id>  Delete one saved session
    lean-ctx discover              Find local opportunities to shape shell output
    lean-ctx discover --card       Shareable 'before' SVG -> lean-ctx-before.svg
    lean-ctx onboard               One-command setup (shell + editors + verify)
    lean-ctx install --repair      Non-interactive repair path (merge-based)
    lean-ctx bootstrap             Non-interactive setup + fix (zero-config)
    lean-ctx bootstrap --json      Machine-readable bootstrap report
    lean-ctx init --global         Install shell aliases (includes lean-ctx-on/off/mode/status)
    lean-ctx-on                    Enable shell aliases in track mode (full output + stats)
    lean-ctx-off                   Disable all shell aliases
    lean-ctx-mode track            Track mode: full output, stats recorded (default)
    LEAN_CTX_DEBUG=1 lean-ctx-on   Show shell hook mode-change notices
    lean-ctx-mode compress         Compress mode: all output compressed (power users)
    lean-ctx-mode off              Same as lean-ctx-off
    lean-ctx-status                Show whether compression is active
    lean-ctx init --agent pi       Install Pi Coding Agent extension
    lean-ctx init --agent grok     Configure Grok (xAI) MCP + hooks
    lean-ctx doctor                Check PATH, config, MCP, and dashboard port
    lean-ctx doctor integrations   Detailed integration checks (Cursor/Claude Code/CodeBuddy)
    lean-ctx doctor --fix --json   Repair + machine-readable report
    lean-ctx status --json         Machine-readable current status
    lean-ctx session task \"implement auth\"
    lean-ctx session finding \"auth.rs:42 — missing validation\"
    lean-ctx knowledge remember \"Uses JWT\" --category auth --key token-type
    lean-ctx knowledge recall \"authentication\"
    lean-ctx knowledge search \"database migration\"
    lean-ctx overview \"refactor auth module\"
    lean-ctx compress --signatures
    lean-ctx read src/main.rs -m map
    lean-ctx grep \"pub fn\" src/
    lean-ctx deps .

GRAPH (project analysis):
    lean-ctx graph build [path]    Build/rebuild project graph index
    lean-ctx graph status          Show graph index statistics
    lean-ctx graph related <file>  List files related to a given file
    lean-ctx graph impact <file>   Show files impacted by changes to a file
    lean-ctx graph symbol <spec>   Inspect a symbol (format: <file>::<symbol>, or bare <symbol>)
    lean-ctx graph context <query> Query the property graph for a concept

PROJECT:
    project status [<path>] [--json]
                                   This checkout: partition, project link, workspace-root choice
    project link --project <team-project-id> [--organization <uuid>] [--label <text>] [<path>]
                                   Checkouts linked to the same project share their knowledge
    project unlink [<path>]        Remove this checkout's project link
    project use <path>             Of several workspace roots, bind sessions to <path> (default: first)
                                   All of it: lean-ctx project help

TROUBLESHOOTING:
    Commands broken?     lean-ctx-off             (fixes current session)
    Permanent fix?       lean-ctx uninstall       (removes all hooks)
    Manual fix?          Edit {rc_file}, remove the \"lean-ctx shell hook\" block
    Binary missing?      Aliases auto-fallback to original commands (safe)
    Preview init?        lean-ctx init --global --dry-run

WEBSITE: https://leanctx.com
GITHUB:  https://github.com/yvgude/lean-ctx
",
        version = env!("CARGO_PKG_VERSION"),
        banner = capability_banner(),
        rc_file = lean_ctx::shell_hook::shell_rc_file(),
        cloud = if lean_ctx_cloud::CLOUD_AVAILABLE {
            "    cloud connect|status|disconnect|link  Connect this machine to the cloud\n    models                         List the models your cloud plan includes\n"
        } else {
            ""
        },
    )
}

pub(super) fn print_help() {
    println!("{}", full_help_text());
}

#[cfg(test)]
mod tests {
    /// #1602: `lean-ctx help all` advertised "watch — Live TUI dashboard
    /// (real-time event stream)" for a command removed in 3.9.20, which then
    /// exited 1 with a bare removal notice. The reference lists what works.
    #[test]
    fn full_help_does_not_advertise_the_removed_tui_dashboard() {
        let text = super::full_help_text();
        assert!(
            !text.contains("Live TUI dashboard"),
            "`help all` must not list the removed TUI dashboard"
        );
        assert!(
            text.contains("cockpit [--port N]"),
            "the Cockpit — the actual replacement — must still be listed"
        );
    }

    /// 3.12.0 ships without Cloud: `help all` lists it only once the release
    /// switch is on.
    #[test]
    fn full_help_lists_cloud_only_when_available() {
        let text = super::full_help_text();
        assert_eq!(
            text.contains("cloud connect"),
            lean_ctx_cloud::CLOUD_AVAILABLE
        );
        assert!(text.contains("    completions <zsh|bash|fish>"));
    }

    /// Owner decisions 15.11./18.11.: help names no bare "Cloud" and no "Pro"
    /// product. rc4-105: help no longer names the product "LeanCTX Cloud"
    /// either. Allowed is only the lowercase word `cloud` (the command name
    /// and plain wording).
    #[test]
    fn help_texts_name_no_cloud_or_pro_product() {
        const ALLOWED: &[&str] = &["cloud"];
        let product = regex::Regex::new(r"LeanCTX\s+[Cc]loud").unwrap();
        fn words(text: &str) -> impl Iterator<Item = &str> {
            text.split(|c: char| !c.is_ascii_alphanumeric())
                .filter(|w| !w.is_empty())
        }
        for (name, text) in [
            ("full", super::full_help_text()),
            ("concise", super::concise_help_text()),
        ] {
            assert!(
                !product.is_match(&text),
                "{name} help names the product `LeanCTX Cloud`"
            );
            for word in words(&text) {
                assert!(
                    !word.eq_ignore_ascii_case("cloud") || ALLOWED.contains(&word),
                    "{name} help names the retired product `{word}`"
                );
                assert!(
                    !word.eq_ignore_ascii_case("pro"),
                    "{name} help names the retired `{word}` plan"
                );
            }
        }
    }

    /// rc4-105 review: the subcommand help texts (`const HELP`/`USAGE`/`MENU`)
    /// and the completion descriptions follow the same rule as `help all`:
    /// no "LeanCTX Cloud" (also not across a line break), no capitalised
    /// "Cloud" mid-text. Sources are scanned so private consts are covered.
    #[test]
    fn subcommand_help_and_completions_name_no_cloud_product() {
        const SOURCES: &[(&str, &str)] = &[
            ("cloud_cmd.rs", include_str!("../cloud_cmd.rs")),
            (
                "cloud_computer_cmd.rs",
                include_str!("../cloud_computer_cmd.rs"),
            ),
            (
                "cloud_computer_runner.rs",
                include_str!("../cloud_computer_runner.rs"),
            ),
            (
                "cloud_consent_cmd.rs",
                include_str!("../cloud_consent_cmd.rs"),
            ),
            (
                "cloud_curate_cmd.rs",
                include_str!("../cloud_curate_cmd.rs"),
            ),
            (
                "cloud_decisions_cmd.rs",
                include_str!("../cloud_decisions_cmd.rs"),
            ),
            ("cloud_docs_cmd.rs", include_str!("../cloud_docs_cmd.rs")),
            ("cloud_tasks_cmd.rs", include_str!("../cloud_tasks_cmd.rs")),
            ("models_cmd.rs", include_str!("../models_cmd.rs")),
            ("run_cmd.rs", include_str!("../run_cmd.rs")),
            ("tasks_cmd.rs", include_str!("../tasks_cmd.rs")),
            (
                "computer_cmd/mod.rs",
                include_str!("../computer_cmd/mod.rs"),
            ),
            (
                "computer_cmd/diag.rs",
                include_str!("../computer_cmd/diag.rs"),
            ),
            (
                "local_read/billing_topup.rs",
                include_str!("../local_read/billing_topup.rs"),
            ),
        ];
        const COMPLETIONS: &[(&str, &str)] = &[
            (
                "spec_account.rs",
                include_str!("../completions/spec_account.rs"),
            ),
            ("spec_team.rs", include_str!("../completions/spec_team.rs")),
            (
                "spec_value.rs",
                include_str!("../completions/spec_value.rs"),
            ),
        ];
        let product = regex::Regex::new(r"LeanCTX\s+(\\\s*)?[Cc]loud").unwrap();
        let capital = regex::Regex::new(r"\bCloud\b").unwrap();
        let help_const = regex::Regex::new(
            r#"(?s)const [A-Z_]*(?:HELP|USAGE|MENU)[A-Z_]*: &str = "(.*?)";\r?\n"#,
        )
        .unwrap();
        let description = regex::Regex::new(r#"description: "([^"]*)""#).unwrap();
        for (file, source) in SOURCES {
            let mut seen = 0;
            for text in help_const.captures_iter(source) {
                seen += 1;
                let text = &text[1];
                assert!(
                    !product.is_match(text),
                    "{file}: help names `LeanCTX Cloud`"
                );
                assert!(
                    !capital.is_match(text),
                    "{file}: help writes `Cloud` capitalised"
                );
            }
            assert!(seen > 0, "{file}: no help const found; update the scan");
        }
        for (file, source) in COMPLETIONS {
            for text in description.captures_iter(source) {
                let text = &text[1];
                assert!(
                    !product.is_match(text),
                    "{file}: `{text}` names `LeanCTX Cloud`"
                );
                assert!(
                    !capital.is_match(text),
                    "{file}: `{text}` writes `Cloud` capitalised"
                );
            }
        }
    }

    /// A string literal found by [`lex`]: where it starts (char index and
    /// line) and its contents with escapes kept.
    struct Literal {
        start: usize,
        line: usize,
        text: String,
    }

    /// Lexes Rust source just far enough to find its string literals: skips
    /// `//` and nested `/* */` comments and char/byte literals (not
    /// lifetimes), and reads `"…"`, `b"…"`, `r#"…"#` and `br#"…"#`, so a
    /// quote outside a string cannot invert the rest of the file, as a
    /// single `"…"` regex did (!714 review). Also returns the source with
    /// comments and literal contents blanked (newlines kept), so code
    /// patterns are not matched inside a fixture string.
    fn lex(src: &str) -> (Vec<Literal>, String) {
        let c: Vec<char> = src.chars().collect();
        let at = |i: usize| c.get(i).copied();
        let ident = |ch: char| ch.is_alphanumeric() || ch == '_';
        let mut masked = c.clone();
        let mut blank = |from: usize, to: usize| {
            for x in masked.iter_mut().take(to.min(c.len())).skip(from) {
                if *x != '\n' {
                    *x = ' ';
                }
            }
        };
        let mut out = Vec::new();
        let (mut i, mut line) = (0, 1);
        while i < c.len() {
            let ch = c[i];
            let raw = match (ch, at(i + 1)) {
                ('r', _) => Some(i + 1),
                ('b', Some('r')) => Some(i + 2),
                _ => None,
            }
            .filter(|_| i == 0 || !ident(c[i - 1]))
            .and_then(|j| {
                let hashes = c[j..].iter().take_while(|&&h| h == '#').count();
                (at(j + hashes) == Some('"')).then_some((j, hashes))
            });
            let from = i;
            if ch == '\n' {
                line += 1;
                i += 1;
            } else if ch == '/' && at(i + 1) == Some('/') {
                while i < c.len() && c[i] != '\n' {
                    i += 1;
                }
                blank(from, i);
            } else if ch == '/' && at(i + 1) == Some('*') {
                let mut depth = 0;
                while i < c.len() {
                    if c[i] == '/' && at(i + 1) == Some('*') {
                        depth += 1;
                        i += 2;
                    } else if c[i] == '*' && at(i + 1) == Some('/') {
                        depth -= 1;
                        i += 2;
                        if depth == 0 {
                            break;
                        }
                    } else {
                        line += usize::from(c[i] == '\n');
                        i += 1;
                    }
                }
                blank(from, i);
            } else if ch == '\'' {
                if at(i + 1) == Some('\\') {
                    // `'\n'`, `'\''`, `'\u{22}'`: past the escaped char,
                    // then to the closing quote.
                    i += 3;
                    while i < c.len() && c[i] != '\'' {
                        i += 1;
                    }
                    i += 1;
                } else if at(i + 2) == Some('\'') {
                    i += 3; // `'x'`, also `'"'`
                } else {
                    i += 1; // a lifetime `'a`
                }
                blank(from + 1, i.saturating_sub(1));
            } else if let Some((j, hashes)) = raw {
                let closes = |k: usize| c[k] == '"' && (1..=hashes).all(|h| at(k + h) == Some('#'));
                let (start_line, body) = (line, j + hashes + 1);
                let mut k = body;
                while k < c.len() && !closes(k) {
                    line += usize::from(c[k] == '\n');
                    k += 1;
                }
                let end = k.min(c.len());
                out.push(Literal {
                    start: from,
                    line: start_line,
                    text: c[body..end].iter().collect(),
                });
                blank(body, end);
                i = k + 1 + hashes;
            } else if ch == '"' {
                let start_line = line;
                i += 1;
                while i < c.len() && c[i] != '"' {
                    let len = if c[i] == '\\' { 2 } else { 1 };
                    line += c.iter().skip(i).take(len).filter(|&&x| x == '\n').count();
                    i += len;
                }
                let end = i.min(c.len());
                out.push(Literal {
                    start: from,
                    line: start_line,
                    text: c[from + 1..end].iter().collect(),
                });
                blank(from + 1, end);
                i += 1;
            } else {
                i += 1;
            }
        }
        (out, masked.into_iter().collect())
    }

    fn names_leanctx_cloud(text: &str) -> bool {
        static PRODUCT: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
        PRODUCT
            .get_or_init(|| regex::Regex::new(r"LeanCTX\s+(\\\s*)?[Cc]loud").unwrap())
            .is_match(text)
    }

    /// Lines of the string literals in `src` that name "LeanCTX Cloud",
    /// outside every inline `#[cfg(test)] mod … { … }` block (found in code
    /// only, other attributes may sit between; the block ends at its
    /// matching `}`, so code after it is scanned again), and whether a
    /// probe literal appended after the whole source came out last, i.e.
    /// the lexer stayed in step through the entire file and every test
    /// block closed.
    fn product_hits(src: &str) -> (Vec<usize>, bool) {
        static TEST_MOD: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
        let test_mod = TEST_MOD.get_or_init(|| {
            regex::Regex::new(
                r"#\[cfg\(test\)\]\s*(?:#\[[^\]]*\]\s*)*(?:pub(?:\([^)]*\))?\s+)?mod\s+\w+\s*\{",
            )
            .unwrap()
        });
        let (literals, masked) = lex(&format!("{src}\n\"LeanCTX Cloud probe\"\n"));
        // Test blocks as char ranges: from the attribute to the `}` that
        // closes the module's `{`. Braces in strings, comments and char
        // literals are blanked in `masked`, so the count holds.
        let chars: Vec<char> = masked.chars().collect();
        let mut blocks = Vec::new();
        let mut from = 0;
        while let Some(m) = test_mod.find_at(&masked, from) {
            let start = masked[..m.start()].chars().count();
            let mut i = masked[..m.end()].chars().count();
            let mut depth = 1;
            while i < chars.len() && depth > 0 {
                depth += usize::from(chars[i] == '{');
                depth -= usize::from(chars[i] == '}');
                i += 1;
            }
            blocks.push(start..i);
            from = masked
                .char_indices()
                .nth(i)
                .map_or(masked.len(), |(byte, _)| byte);
        }
        let in_step = literals.last().is_some_and(|l| {
            l.text == "LeanCTX Cloud probe" && !blocks.iter().any(|b| b.contains(&l.start))
        });
        let hits = literals
            .iter()
            .take(literals.len().saturating_sub(1))
            .filter(|l| !blocks.iter().any(|b| b.contains(&l.start)))
            .filter(|l| names_leanctx_cloud(&l.text))
            .map(|l| l.line)
            .collect();
        (hits, in_step)
    }

    /// The lexer stays in step after every construct that tripped the regex
    /// pairing (!714 review): each fixture must report exactly the hit on
    /// the line after it; a hit inside a comment or inside an inline test
    /// module is no hit, code after a test module (also with nested braces)
    /// is scanned, and a test module inside a fixture string is no module.
    #[test]
    fn string_literal_lexer_survives_quotes_outside_strings() {
        let fixtures = [
            r#"let q = '"';"#,
            r#"x(); // ""#,
            r##"let s = r#"a"b"#;"##,
            r###"let s = br##"x"#y"##;"###,
            r#"/* " */"#,
            r#"/* /* " */ " */"#,
            "fn f<'a>(x: &'a str) -> &'a str { x }",
            r#"let b = b'"';"#,
            r"let e = '\'';",
            r"let u = '\u{22}';",
            r#"let s = "a\"b // /*";"#,
            "let r#type = 1;",
            "let s = r#\"\n#[cfg(test)]\nmod tests {\n\"#;",
        ];
        for fixture in fixtures {
            let source = format!("{fixture}\n\"LeanCTX Cloud\"");
            let line = fixture.lines().count() + 1;
            assert_eq!(
                product_hits(&source),
                (vec![line], true),
                "after `{fixture}`"
            );
        }
        for (source, expected) in [
            ("// \"LeanCTX Cloud\"", vec![]),
            ("/* \"LeanCTX Cloud\" */", vec![]),
            ("let s = r#\"LeanCTX Cloud\"#;", vec![1]),
            ("let s = \"LeanCTX \\\n    Cloud\";", vec![1]),
            (
                "#[cfg(test)]\n#[cfg(feature = \"x\")]\nmod tests {\n    \"LeanCTX Cloud\"\n}",
                vec![],
            ),
            ("#[cfg(test)]\nmod tests;\n\"LeanCTX Cloud\"", vec![3]),
            // !714 review 2: code after a test block is scanned again.
            (
                "#[cfg(test)]\nmod failpoints {\n    fn f() { \"LeanCTX Cloud\"; }\n}\nfn g() { \"LeanCTX Cloud\"; }",
                vec![5],
            ),
            (
                "#[cfg(test)]\nmod a {\n    mod b { fn f() { let c = '}'; \"x\"; } }\n    \"LeanCTX Cloud\"\n}\n\"LeanCTX Cloud\"",
                vec![6],
            ),
            (
                "#[cfg(test)]\nmod a { \"LeanCTX Cloud\" }\nfn m() {}\n#[cfg(test)]\nmod b { \"LeanCTX Cloud\" }\n\"LeanCTX Cloud\"",
                vec![6],
            ),
        ] {
            assert_eq!(product_hits(source), (expected, true), "in `{source}`");
        }
    }

    /// !713 review: the help scans above miss error and status messages, so
    /// three of them still said "LeanCTX Cloud". This one lexes every string
    /// literal in the workspace's non-test sources (engine and all crates):
    /// comments, inline `#[cfg(test)] mod … { … }` blocks, `*tests.rs` and
    /// `tests_*.rs` files and `tests/` directories are skipped, so ban lists
    /// and fixtures stay allowed. A probe literal appended to every file
    /// must come out last, so the lexer cannot go blind silently.
    #[test]
    fn no_string_literal_names_the_leanctx_cloud_product() {
        let workspace = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../..")
            .canonicalize()
            .unwrap();
        let mut roots = vec![workspace.join("src")];
        for entry in std::fs::read_dir(workspace.join("crates")).unwrap() {
            roots.push(entry.unwrap().path().join("src"));
        }
        let mut scanned = 0;
        let mut found = Vec::new();
        let mut blind = Vec::new();
        for root in roots.iter().filter(|r| r.is_dir()) {
            for entry in walkdir::WalkDir::new(root) {
                let entry = entry.unwrap();
                let path = entry.path();
                let name = path.file_name().unwrap_or_default().to_string_lossy();
                if !name.ends_with(".rs")
                    || name.ends_with("tests.rs")
                    || name.starts_with("tests_")
                    || path.components().any(|c| c.as_os_str() == "tests")
                {
                    continue;
                }
                let rel = path.strip_prefix(&workspace).unwrap_or(path).display();
                let (hits, in_step) = product_hits(&std::fs::read_to_string(path).unwrap());
                if !in_step {
                    blind.push(rel.to_string());
                }
                found.extend(hits.into_iter().map(|line| format!("{rel}:{line}")));
                scanned += 1;
            }
        }
        assert!(
            scanned > 100,
            "only {scanned} sources scanned; update the walk"
        );
        assert!(blind.is_empty(), "the lexer lost step in {blind:?}");
        assert!(
            found.is_empty(),
            "user-facing strings name `LeanCTX Cloud` (say \"the Cloud\"): {found:?}"
        );
    }
}