loctree 0.8.16

Structural code intelligence for AI agents. Scan once, query everything.
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
//! Help text generation for CLI commands.
//!
//! VibeCrafted with AI Agents (c)2026 Loctree Team

use super::help_texts::*;
use super::types::Command;

impl Command {
    /// Get the command name as a string.
    pub fn name(&self) -> &'static str {
        match self {
            Command::Auto(_) => "auto",
            Command::Scan(_) => "scan",
            Command::Tree(_) => "tree",
            Command::Slice(_) => "slice",
            Command::Find(_) => "find",
            Command::Dead(_) => "dead",
            Command::Cycles(_) => "cycles",
            Command::Trace(_) => "trace",
            Command::Commands(_) => "commands",
            Command::Routes(_) => "routes",
            Command::Events(_) => "events",
            Command::Pipelines(_) => "pipelines",
            Command::Insights(_) => "insights",
            Command::Manifests(_) => "manifests",
            Command::Info(_) => "info",
            Command::Lint(_) => "lint",
            Command::Report(_) => "report",
            Command::Findings(_) => "findings",
            Command::Help(_) => "help",
            Command::Version => "version",
            Command::Query(_) => "query",
            Command::Diff(_) => "diff",
            Command::Memex(_) => "memex",
            Command::Crowd(_) => "crowd",
            Command::Tagmap(_) => "tagmap",
            Command::Twins(_) => "twins",
            Command::Suppress(_) => "suppress",
            Command::Dist(_) => "dist",
            Command::Coverage(_) => "coverage",
            Command::Sniff(_) => "sniff",
            Command::JqQuery(_) => "jq",
            Command::Impact(_) => "impact",
            Command::Focus(_) => "focus",
            Command::Hotspots(_) => "hotspots",
            Command::Layoutmap(_) => "layoutmap",
            Command::Zombie(_) => "zombie",
            Command::Health(_) => "health",
            Command::Audit(_) => "audit",
            Command::Doctor(_) => "doctor",
            Command::Plan(_) => "plan",
            Command::Cache(_) => "cache",
        }
    }

    /// Get a short description of the command.
    pub fn description(&self) -> &'static str {
        match self {
            Command::Auto(_) => "Full auto-scan with stack detection (default)",
            Command::Scan(_) => "Build/update snapshot for current HEAD (supports --watch)",
            Command::Tree(_) => "Display LOC tree / structural overview",
            Command::Slice(_) => "Extract holographic context for a file",
            Command::Find(_) => "Search symbols/files with regex filters",
            Command::Dead(_) => "Detect unused exports / dead code",
            Command::Cycles(_) => "Detect circular imports",
            Command::Trace(_) => "Trace a Tauri/IPC handler end-to-end",
            Command::Commands(_) => "Show Tauri command bridges (FE <-> BE)",
            Command::Events(_) => "Show event flow and issues",
            Command::Pipelines(_) => "Show pipeline summary (events/commands/risks)",
            Command::Insights(_) => "Show AI insights summary",
            Command::Manifests(_) => "Show manifest summaries (package.json/Cargo.toml)",
            Command::Info(_) => "Show snapshot metadata and project info",
            Command::Lint(_) => "Structural lint/policy checks",
            Command::Report(_) => "Generate HTML report + cached artifacts",
            Command::Findings(_) => "Emit the canonical findings artifact for agents and CI",
            Command::Help(_) => "Show help for commands",
            Command::Version => "Show version information",
            Command::Query(_) => "Query snapshot data (who-imports, where-symbol, component-of)",
            Command::Diff(_) => "Compare snapshots and show semantic delta",
            Command::Memex(_) => "Index analysis into AI memory (vector DB)",
            Command::Crowd(_) => "Detect functional crowds (similar files clustering)",
            Command::Tagmap(_) => "Unified search: files + crowd + dead around a keyword",
            Command::Twins(_) => "Show symbol registry and dead parrots (0 imports)",
            Command::Suppress(_) => "Manage false positive suppressions",
            Command::Routes(_) => "List backend/web routes (FastAPI/Flask)",
            Command::Dist(_) => "Verify tree-shaking from production source maps",
            Command::Coverage(_) => "Analyze test coverage gaps (structural coverage)",
            Command::Sniff(_) => "Sniff for code smells (twins + dead parrots + crowds)",
            Command::JqQuery(_) => "Query snapshot with jq-style filters (loct '.filter')",
            Command::Impact(_) => "Analyze impact of modifying/removing a file",
            Command::Focus(_) => "Extract holographic context for a directory",
            Command::Hotspots(_) => "Show import frequency heatmap (core vs peripheral)",
            Command::Layoutmap(_) => "Analyze CSS layout (z-index, position, grid/flex)",
            Command::Zombie(_) => "Find zombie code (dead exports + orphan files + shadows)",
            Command::Health(_) => "Quick health check (cycles + dead + twins summary)",
            Command::Audit(_) => "Full audit (cycles + dead + twins + zombie + crowds)",
            Command::Doctor(_) => "Interactive diagnostics with actionable recommendations",
            Command::Plan(_) => "Generate architectural refactoring plan",
            Command::Cache(_) => "Manage snapshot cache (list, clean)",
        }
    }

    /// Generate the main help text listing the core commands.
    pub fn format_help() -> String {
        let mut help = String::new();
        help.push_str(&format!(
            "loctree {} - AI-oriented codebase analyzer\n\n",
            env!("CARGO_PKG_VERSION")
        ));

        help.push_str("SCAN (produces artifacts):\n");
        help.push_str("  loct                  Analyze -> cached artifacts (see LOCT_CACHE_DIR)\n");
        help.push_str("  loct --fresh          Ignore cache, full rescan\n");
        help.push_str("  loct --watch          Continuous scan on file changes\n\n");

        help.push_str("QUERY (reads artifacts):\n");
        help.push_str("  loct slice <file>     Context for a file (deps + consumers)\n");
        help.push_str("  loct find <pattern>   Search symbols across languages\n");
        help.push_str("  loct '<jq-query>'     Query any artifact with jq\n");
        help.push_str(
            "  loct query <type>     Graph: who-imports, where-defined, component-of\n\n",
        );

        help.push_str("OUTPUT (stdout, pipe-friendly):\n");
        help.push_str("  loct --for-ai         AI context bundle\n");
        help.push_str("  loct findings         Full findings JSON\n");
        help.push_str("  loct findings --summary Health score + counts only\n\n");

        help.push_str("ALIASES:\n");
        help.push_str("  loct h                = health (quick sanity check)\n");
        help.push_str("  loct d                = dead (unused exports)\n");
        help.push_str("  loct t                = twins (dead parrots + duplicates)\n");
        help.push_str("  loct c                = cycles (circular imports)\n");
        help.push_str("  loct s <file>         = slice (file context)\n");
        help.push_str("  loct f <pattern>      = find (symbol search)\n");
        help.push_str("  loct i <file>         = impact (what breaks?)\n");
        help.push_str("  loct q <kind> <tgt>   = query (graph queries)\n\n");

        help.push_str("ARTIFACTS (default: user cache dir; override via LOCT_CACHE_DIR):\n");
        help.push_str("  snapshot.json            Graph data (jq-able)\n");
        help.push_str("  findings.json            All issues (dead, cycles, twins...)\n");
        help.push_str("  agent.json               AI bundle\n");
        help.push_str("  manifest.json            Index for tooling\n\n");

        help.push_str("PROJECT CONFIG (repo-local, optional):\n");
        help.push_str("  .loctree/config.toml       Custom rules/macros\n");
        help.push_str("  .loctree/suppressions.toml Suppress findings\n\n");

        help.push_str("GLOBAL OPTIONS:\n");
        help.push_str("    --json           Output as JSON (stdout only)\n");
        help.push_str("    --quiet          Suppress non-essential output\n");
        help.push_str("    --verbose        Show detailed progress\n");
        help.push_str("    --color <mode>   Color mode: auto|always|never\n");
        help.push_str("    --fresh          Force rescan even if snapshot exists\n");
        help.push_str("    --no-scan        Fail if no snapshot (don't auto-scan)\n");
        help.push_str("    --fail-stale     Fail if snapshot is stale (CI mode)\n");
        help.push_str("    --py-root <path> Additional Python package root for imports\n");
        help.push_str("    --help           Show this help\n");
        help.push_str("    --version        Show version\n\n");

        help.push_str("ANALYSIS:\n");
        help.push_str("  loct dead             Find unused exports\n");
        help.push_str("  loct cycles           Circular imports\n");
        help.push_str("  loct twins            Dead parrots + duplicates\n");
        help.push_str("  loct health           Quick health check\n");
        help.push_str("  loct findings         Full findings JSON\n");
        help.push_str("  loct dist             Verify tree-shaking from source maps\n");
        help.push_str("  loct audit            Full codebase audit\n\n");

        help.push_str("WORKFLOWS:\n");
        help.push_str("  loct doctor           Triage findings with recommendations\n");
        help.push_str("  loct report           Full HTML report + cached artifacts\n\n");

        help.push_str("INSTANT (<100ms):\n");
        help.push_str("  loct focus <dir>      Directory context\n");
        help.push_str("  loct hotspots         Import frequency heatmap\n");
        help.push_str("  loct commands         Tauri FE↔BE bridges\n");
        help.push_str("  loct pipelines        Pipeline summary (events/commands)\n");
        help.push_str("  loct insights         AI insights summary\n");
        help.push_str("  loct manifests        Manifest summaries\n");
        help.push_str("  loct coverage         Test coverage gaps\n");
        help.push_str("  loct impact <file>    What breaks if changed\n\n");

        help.push_str("MORE:\n");
        help.push_str("  loct --help-full      All commands\n");
        help.push_str("  loct <cmd> --help     Per-command help\n");
        help.push_str("  loct --help-legacy    Deprecated flag migration\n");

        help
    }

    /// Generate help text for a specific subcommand (new CLI).
    pub fn format_command_help(command: &str) -> Option<&'static str> {
        match command {
            "auto" => Some(AUTO_HELP),
            "agent" => Some(AGENT_HELP),
            "scan" => Some(SCAN_HELP),
            "tree" => Some(TREE_HELP),
            "slice" => Some(SLICE_HELP),
            "find" => Some(FIND_HELP),
            "dead" | "unused" => Some(DEAD_HELP),
            "cycles" => Some(CYCLES_HELP),
            "trace" => Some(TRACE_HELP),
            "commands" => Some(COMMANDS_HELP),
            "events" => Some(EVENTS_HELP),
            "pipelines" => Some(PIPELINES_HELP),
            "insights" => Some(INSIGHTS_HELP),
            "manifests" => Some(MANIFESTS_HELP),
            "info" => Some(INFO_HELP),
            "lint" => Some(LINT_HELP),
            "report" => Some(REPORT_HELP),
            "findings" => Some(FINDINGS_HELP),
            "query" => Some(QUERY_HELP),
            "impact" => Some(IMPACT_HELP),
            "diff" => Some(DIFF_HELP),
            "memex" => Some(MEMEX_HELP),
            "crowd" => Some(CROWD_HELP),
            "tagmap" => Some(TAGMAP_HELP),
            "twins" => Some(TWINS_HELP),
            "routes" => Some(ROUTES_HELP),
            "dist" => Some(DIST_HELP),
            "coverage" => Some(COVERAGE_HELP),
            "sniff" => Some(SNIFF_HELP),
            "suppress" => Some(SUPPRESS_HELP),
            "focus" => Some(FOCUS_HELP),
            "hotspots" => Some(HOTSPOTS_HELP),
            "layoutmap" => Some(LAYOUTMAP_HELP),
            "zombie" => Some(ZOMBIE_HELP),
            "health" => Some(HEALTH_HELP),
            "audit" => Some(AUDIT_HELP),
            "doctor" => Some(DOCTOR_HELP),
            "jq" => Some(JQ_HELP),
            "plan" | "p" => Some(PLAN_HELP),
            _ => None,
        }
    }

    /// Generate the full help text with ALL commands (auto-generated).
    /// This replaces the hardcoded format_usage_full() in loct.rs.
    pub fn format_help_full() -> String {
        let mut help = String::new();
        help.push_str(&format!(
            "loctree {} - AI-oriented codebase analyzer (Full Reference)\n\n",
            env!("CARGO_PKG_VERSION")
        ));

        help.push_str("PHILOSOPHY: Scan once, query everything.\n");
        help.push_str(
            "            Run `loct` to create artifacts, then query with subcommands.\n\n",
        );

        // === INSTANT COMMANDS (< 100ms) ===
        help.push_str("=== INSTANT COMMANDS (<100ms) ===\n\n");
        let instant_cmds = [
            ("focus <dir>", "Holographic context for a directory"),
            ("hotspots", "Import frequency heatmap (core vs peripheral)"),
            ("commands", "Tauri FE↔BE handler bridges"),
            ("events", "Event emit/listen flow analysis"),
            ("pipelines", "Pipeline summary (events/commands/risks)"),
            ("insights", "AI insights summary"),
            ("manifests", "Manifest summaries (package.json/Cargo.toml)"),
            ("coverage", "Test coverage gaps (structural)"),
            ("health", "Quick health check (cycles + dead + twins)"),
            ("findings", "Full findings JSON or summary for pipes/CI"),
            ("slice <file>", "Context for a file (deps + consumers)"),
            ("impact <file>", "What breaks if you modify this file"),
            ("query <type>", "Graph queries (who-imports, where-symbol)"),
        ];
        for (cmd, desc) in instant_cmds {
            help.push_str(&format!("  loct {:<16} {}\n", cmd, desc));
        }
        help.push('\n');

        // === ANALYSIS COMMANDS ===
        help.push_str("=== ANALYSIS COMMANDS ===\n\n");
        let analysis_cmds = [
            ("dead", "Find unused exports / dead code"),
            ("cycles", "Detect circular import chains"),
            ("twins", "Find dead parrots (0 imports) + duplicate exports"),
            ("zombie", "Combined: dead + orphan files + shadows"),
            ("audit", "Full codebase audit (all checks)"),
            ("crowd <kw>", "Functional clustering around keyword"),
            ("tagmap <kw>", "Unified search: files + crowd + dead"),
            ("sniff", "Code smells aggregate (twins + dead + crowds)"),
        ];
        for (cmd, desc) in analysis_cmds {
            help.push_str(&format!("  loct {:<16} {}\n", cmd, desc));
        }
        help.push('\n');

        // === FRAMEWORK-SPECIFIC ===
        help.push_str("=== FRAMEWORK-SPECIFIC ===\n\n");
        let framework_cmds = [
            ("trace <handler>", "Trace Tauri handler end-to-end"),
            ("routes", "List FastAPI/Flask routes"),
            ("dist", "Verify tree-shaking from one or more source maps"),
            ("layoutmap", "CSS z-index/position/grid analysis"),
        ];
        for (cmd, desc) in framework_cmds {
            help.push_str(&format!("  loct {:<16} {}\n", cmd, desc));
        }
        help.push('\n');

        // === MANAGEMENT ===
        help.push_str("=== MANAGEMENT ===\n\n");
        let mgmt_cmds = [
            ("doctor", "Interactive diagnostics with recommendations"),
            ("suppress", "Manage false positive suppressions"),
            ("diff", "Compare snapshots between branches/commits"),
            ("memex", "Index analysis into AI memory (vector DB)"),
        ];
        for (cmd, desc) in mgmt_cmds {
            help.push_str(&format!("  loct {:<16} {}\n", cmd, desc));
        }
        help.push('\n');

        // === CORE WORKFLOW ===
        help.push_str("=== CORE WORKFLOW ===\n\n");
        let core_cmds = [
            ("auto", "Full scan → cached artifacts (see LOCT_CACHE_DIR)"),
            ("scan", "Build/update snapshot (supports --watch)"),
            ("tree", "Directory tree with LOC counts"),
            ("find <pattern>", "Search symbols/files with regex"),
            ("findings", "Emit findings JSON to stdout"),
            ("report", "Generate HTML report + cached artifacts"),
            ("lint", "Structural lint and policy checks"),
        ];
        for (cmd, desc) in core_cmds {
            help.push_str(&format!("  loct {:<16} {}\n", cmd, desc));
        }
        help.push('\n');

        // === JQ QUERIES ===
        help.push_str("=== JQ QUERIES ===\n\n");
        help.push_str("  loct '.metadata'              Extract metadata from snapshot\n");
        help.push_str("  loct '.files | length'        Count analyzed files\n");
        help.push_str("  loct '.dead_parrots[]'        List dead exports\n");
        help.push_str("  loct '.cycles[]'              List circular imports\n\n");

        // === GLOBAL OPTIONS ===
        help.push_str("=== GLOBAL OPTIONS ===\n\n");
        help.push_str("  --json             Output as JSON\n");
        help.push_str("  --fresh            Force rescan (ignore cache)\n");
        help.push_str("  --verbose          Detailed progress\n");
        help.push_str("  --fail             Exit non-zero on findings (CI mode)\n");
        help.push_str("  --sarif            SARIF 2.1.0 output for CI\n\n");

        // === ARTIFACTS ===
        help.push_str("=== ARTIFACTS ===\n\n");
        help.push_str("  (default: user cache dir; override via LOCT_CACHE_DIR)\n\n");
        help.push_str("  snapshot.json      Full dependency graph (jq-queryable)\n");
        help.push_str("  findings.json      All issues (dead, cycles, twins...)\n");
        help.push_str("  agent.json         AI-optimized bundle with health_score\n");
        help.push_str("  manifest.json      Index for tooling integration\n\n");

        help.push_str("PROJECT CONFIG (repo-local, optional):\n");
        help.push_str("  .loctree/config.toml       Custom rules/macros\n");
        help.push_str("  .loctree/suppressions.toml Suppress findings\n\n");

        // === PER-COMMAND HELP ===
        help.push_str("=== PER-COMMAND HELP ===\n\n");
        help.push_str("  loct <command> --help    Detailed help for any command\n");
        help.push_str("  loct --help-legacy       Legacy flag migration guide\n\n");

        // === EXAMPLES ===
        help.push_str("=== EXAMPLES ===\n\n");
        help.push_str("  # Quick analysis\n");
        help.push_str("  loct                       # Scan repo, create artifacts\n");
        help.push_str("  loct health                # Quick health check\n");
        help.push_str("  loct findings --summary    # Summary JSON for CI\n");
        help.push_str("  loct hotspots              # Find hub files (47ms!)\n\n");

        help.push_str("  # Deep analysis\n");
        help.push_str("  loct focus src/features/   # Directory context (67ms!)\n");
        help.push_str("  loct coverage              # Test gaps (49ms!)\n");
        help.push_str("  loct audit                 # Full audit\n\n");

        help.push_str("  # AI integration\n");
        help.push_str("  loct slice src/main.rs --json | claude\n");
        help.push_str("  loct findings > findings.json\n");
        help.push_str("  loct --for-ai > context.json\n\n");

        help.push_str("  # CI integration\n");
        help.push_str("  loct lint --fail --sarif > loctree.sarif\n");
        help.push_str("  loct health --json | jq '.summary.health_score'\n");

        help
    }

    /// Generate legacy help text with migration hints.
    pub fn format_legacy_help() -> String {
        let mut help = String::new();
        help.push_str("loctree - Legacy Flag Reference\n\n");
        help.push_str("These flags are deprecated and will be removed in v1.0.\n");
        help.push_str("Please migrate to the new subcommand interface.\n\n");

        help.push_str("LEGACY FLAG              -> NEW COMMAND\n");
        help.push_str("-------------------------------------------\n");
        help.push_str("loct                     -> loct auto (unchanged)\n");
        help.push_str("loct --tree              -> loct tree\n");
        help.push_str("loct -A                  -> loct report\n");
        help.push_str("loct -A --dead           -> loct dead\n");
        help.push_str("loct -A --circular       -> loct cycles\n");
        help.push_str("loct -A --entrypoints    -> loct lint --entrypoints\n");
        help.push_str("loct -A --symbol NAME    -> loct find --symbol NAME\n");
        help.push_str("loct -A --impact FILE    -> loct find --impact FILE\n");
        help.push_str("loct --findings          -> loct findings\n");
        help.push_str("loct --summary           -> loct findings --summary\n");
        help.push_str("loct --for-ai            -> loct auto --agent-json\n");
        help.push_str("loct slice PATH          -> loct slice PATH (unchanged)\n");

        help.push_str("\nFor the new command reference, run: loct --help\n");

        help
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::command::options::{
        CyclesOptions, DeadOptions, ScanOptions, SliceOptions, TreeOptions,
    };

    #[test]
    fn test_command_default_is_auto() {
        let cmd = Command::default();
        assert_eq!(cmd.name(), "auto");
    }

    #[test]
    fn test_command_names() {
        assert_eq!(Command::Scan(ScanOptions::default()).name(), "scan");
        assert_eq!(Command::Tree(TreeOptions::default()).name(), "tree");
        assert_eq!(Command::Slice(SliceOptions::default()).name(), "slice");
        assert_eq!(Command::Dead(DeadOptions::default()).name(), "dead");
        assert_eq!(Command::Cycles(CyclesOptions::default()).name(), "cycles");
    }

    #[test]
    fn test_help_format_contains_commands() {
        let help = Command::format_help();
        assert!(help.contains("slice"));
        assert!(help.contains("find"));
        assert!(help.contains("findings"));
    }

    #[test]
    fn test_legacy_help_format_contains_mappings() {
        let help = Command::format_legacy_help();
        assert!(help.contains("--tree"));
        assert!(help.contains("-A --dead"));
        assert!(help.contains("loct dead"));
    }

    #[test]
    fn test_command_specific_help_exists() {
        let tree_help = Command::format_command_help("tree").unwrap();
        assert!(tree_help.contains("loct tree"));
        let findings_help = Command::format_command_help("findings").unwrap();
        assert!(findings_help.contains("loct findings"));
        assert!(Command::format_command_help("unknown").is_none());
    }
}