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
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
//! Parsers for output/reporting commands: report, findings, info, lint, diff, memex, jq_query.
//!
//! These commands generate reports, output analysis results, and support different formats.

use std::path::PathBuf;

use super::super::command::{
    Command, DiffOptions, FindingsOptions, GlobalOptions, HelpOptions, InfoOptions,
    InsightsOptions, JqQueryOptions, LintOptions, ManifestsOptions, MemexOptions, ParsedCommand,
    PipelinesOptions, ReportOptions,
};
use super::helpers::is_jq_filter;

/// Parse `loct info [path]` command - show snapshot metadata.
pub(super) fn parse_info_command(args: &[String]) -> Result<Command, String> {
    // Check for help flag first
    if args.iter().any(|a| a == "--help" || a == "-h") {
        return Err("loct info - Show snapshot metadata and project info

USAGE:
    loct info [PATH]

ARGUMENTS:
    [PATH]     Root directory to analyze (default: current directory)

OPTIONS:
    --help, -h   Show this help message

EXAMPLES:
    loct info
    loct info src/"
            .to_string());
    }

    let mut opts = InfoOptions::default();
    let mut i = 0;

    while i < args.len() {
        let arg = &args[i];
        match arg.as_str() {
            _ if !arg.starts_with('-') => {
                opts.root = Some(PathBuf::from(arg));
                i += 1;
            }
            _ => {
                return Err(format!("Unknown option '{}' for 'info' command.", arg));
            }
        }
    }

    Ok(Command::Info(opts))
}

/// Parse `loct lint [options]` command - structural lint and policy checks.
pub(super) fn parse_lint_command(args: &[String]) -> Result<Command, String> {
    // Check for help flag first
    if args.iter().any(|a| a == "--help" || a == "-h") {
        return Err("loct lint - Structural lint and policy checks

USAGE:
    loct lint [OPTIONS] [PATHS...]

OPTIONS:
    --entrypoints    Validate entrypoint files exist and are properly configured
    --fail           Exit with code 1 if any violations found (CI mode)
    --sarif          Output in SARIF format (GitHub Code Scanning compatible)
    --tauri          Enable Tauri-specific contract checks (commands, events)
    --deep           Include ts/react/memory lint checks
    --ts             Include TypeScript lint checks
    --react          Include React lint checks
    --memory         Include memory leak lint checks
    --no-duplicates  Hide duplicate export sections in CLI output
    --no-dynamic-imports Hide dynamic import sections in CLI output
    --help, -h       Show this help message

EXAMPLES:
    loct lint
    loct lint --fail"
            .to_string());
    }

    let mut opts = LintOptions::default();
    let mut i = 0;

    while i < args.len() {
        let arg = &args[i];
        match arg.as_str() {
            "--entrypoints" => {
                opts.entrypoints = true;
                i += 1;
            }
            "--fail" => {
                opts.fail = true;
                i += 1;
            }
            "--sarif" => {
                opts.sarif = true;
                i += 1;
            }
            "--tauri" => {
                opts.tauri = true;
                i += 1;
            }
            "--deep" => {
                opts.deep = true;
                i += 1;
            }
            "--ts" => {
                opts.ts = true;
                i += 1;
            }
            "--react" => {
                opts.react = true;
                i += 1;
            }
            "--memory" => {
                opts.memory = true;
                i += 1;
            }
            "--no-duplicates" => {
                opts.suppress_duplicates = true;
                i += 1;
            }
            "--no-dynamic-imports" => {
                opts.suppress_dynamic = true;
                i += 1;
            }
            _ if !arg.starts_with('-') => {
                opts.roots.push(PathBuf::from(arg));
                i += 1;
            }
            _ => {
                return Err(format!("Unknown option '{}' for 'lint' command.", arg));
            }
        }
    }

    if opts.roots.is_empty() {
        opts.roots.push(PathBuf::from("."));
    }

    Ok(Command::Lint(opts))
}

/// Parse `loct pipelines [options]` command - pipeline summary.
pub(super) fn parse_pipelines_command(args: &[String]) -> Result<Command, String> {
    if args.iter().any(|a| a == "--help" || a == "-h") {
        return Err("loct pipelines - Pipeline summary (events/commands/risks)

USAGE:
    loct pipelines [PATHS...]

OPTIONS:
    --help, -h   Show this help message

EXAMPLES:
    loct pipelines
    loct pipelines ."
            .to_string());
    }

    let mut opts = PipelinesOptions::default();
    let mut i = 0;
    while i < args.len() {
        let arg = &args[i];
        match arg.as_str() {
            _ if !arg.starts_with('-') => {
                opts.roots.push(PathBuf::from(arg));
                i += 1;
            }
            _ => {
                return Err(format!("Unknown option '{}' for 'pipelines' command.", arg));
            }
        }
    }

    if opts.roots.is_empty() {
        opts.roots.push(PathBuf::from("."));
    }

    Ok(Command::Pipelines(opts))
}

/// Parse `loct insights [options]` command - AI insights.
pub(super) fn parse_insights_command(args: &[String]) -> Result<Command, String> {
    if args.iter().any(|a| a == "--help" || a == "-h") {
        return Err("loct insights - AI insights summary

USAGE:
    loct insights [PATHS...]

OPTIONS:
    --help, -h   Show this help message

EXAMPLES:
    loct insights
    loct insights ."
            .to_string());
    }

    let mut opts = InsightsOptions::default();
    let mut i = 0;
    while i < args.len() {
        let arg = &args[i];
        match arg.as_str() {
            _ if !arg.starts_with('-') => {
                opts.roots.push(PathBuf::from(arg));
                i += 1;
            }
            _ => {
                return Err(format!("Unknown option '{}' for 'insights' command.", arg));
            }
        }
    }

    if opts.roots.is_empty() {
        opts.roots.push(PathBuf::from("."));
    }

    Ok(Command::Insights(opts))
}

/// Parse `loct manifests [options]` command - manifest summaries.
pub(super) fn parse_manifests_command(args: &[String]) -> Result<Command, String> {
    if args.iter().any(|a| a == "--help" || a == "-h") {
        return Err("loct manifests - Manifest summaries

USAGE:
    loct manifests [PATHS...]

OPTIONS:
    --help, -h   Show this help message

EXAMPLES:
    loct manifests
    loct manifests ."
            .to_string());
    }

    let mut opts = ManifestsOptions::default();
    let mut i = 0;
    while i < args.len() {
        let arg = &args[i];
        match arg.as_str() {
            _ if !arg.starts_with('-') => {
                opts.roots.push(PathBuf::from(arg));
                i += 1;
            }
            _ => {
                return Err(format!("Unknown option '{}' for 'manifests' command.", arg));
            }
        }
    }

    if opts.roots.is_empty() {
        opts.roots.push(PathBuf::from("."));
    }

    Ok(Command::Manifests(opts))
}

/// Parse `loct findings [options]` command - emit canonical findings JSON.
pub(super) fn parse_findings_command(args: &[String]) -> Result<Command, String> {
    if args.iter().any(|a| a == "--help" || a == "-h") {
        return Err("loct findings - Emit the canonical findings artifact

USAGE:
    loct findings [OPTIONS] [PATHS...]

DESCRIPTION:
    Writes the canonical findings artifact to stdout as JSON.
    This is the machine-truth surface for dead code, cycles, duplicates,
    entrypoint drift, quick wins, and related health signals.

OPTIONS:
    --summary          Emit health score + counts only
    --help, -h         Show this help message

ARGUMENTS:
    [PATHS...]         Root directories to analyze (default: current directory)

EXAMPLES:
    loct findings
    loct findings --summary
    loct findings . | jq '.dead_parrots | length'"
            .to_string());
    }

    let mut opts = FindingsOptions::default();
    let mut i = 0;

    while i < args.len() {
        let arg = &args[i];
        match arg.as_str() {
            "--summary" => {
                opts.summary = true;
                i += 1;
            }
            _ if !arg.starts_with('-') => {
                opts.roots.push(PathBuf::from(arg));
                i += 1;
            }
            _ => {
                return Err(format!("Unknown option '{}' for 'findings' command.", arg));
            }
        }
    }

    if opts.roots.is_empty() {
        opts.roots.push(PathBuf::from("."));
    }

    Ok(Command::Findings(opts))
}

/// Parse `loct report [options]` command - generate HTML report + cached artifacts.
pub(super) fn parse_report_command(args: &[String]) -> Result<Command, String> {
    // Check for help flag first
    if args.iter().any(|a| a == "--help" || a == "-h") {
        return Err("loct report - Generate HTML report + cached artifacts

USAGE:
    loct report [OPTIONS] [PATHS...]

DESCRIPTION:
    Runs full analysis and writes the full HTML report plus cached artifacts
    such as findings.json, agent.json, analysis.json, and report.sarif.

OPTIONS:
    --output, -o <FILE>  Write HTML report to file (default: auto-generate name)
    --serve              Start HTTP server to view report
    --port <PORT>        Server port (default: 8080, with --serve)
    --editor <EDITOR>    Editor for click-to-open (code, cursor, windsurf, jetbrains)
    --help, -h           Show this help message

EXAMPLES:
    loct report
    loct report --output report.html
    loct report --serve"
            .to_string());
    }

    let mut opts = ReportOptions::default();
    let mut i = 0;

    while i < args.len() {
        let arg = &args[i];
        match arg.as_str() {
            "--format" => {
                return Err(
                    "`loct report --format` is not supported. `loct report` writes HTML plus cached artifacts; use `loct findings` or the saved JSON artifacts for machine-readable output.".to_string(),
                );
            }
            "--output" | "-o" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--output requires a file path".to_string())?;
                opts.output = Some(PathBuf::from(value));
                i += 2;
            }
            "--serve" => {
                opts.serve = true;
                i += 1;
            }
            "--port" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--port requires a number".to_string())?;
                opts.port = Some(value.parse().map_err(|_| "--port requires a number")?);
                i += 2;
            }
            "--editor" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--editor requires a value".to_string())?;
                opts.editor = Some(value.clone());
                i += 2;
            }
            _ if !arg.starts_with('-') => {
                opts.roots.push(PathBuf::from(arg));
                i += 1;
            }
            _ => {
                return Err(format!("Unknown option '{}' for 'report' command.", arg));
            }
        }
    }

    if opts.roots.is_empty() {
        opts.roots.push(PathBuf::from("."));
    }

    Ok(Command::Report(opts))
}

/// Parse `loct diff [options]` command - compare snapshots.
pub(super) fn parse_diff_command(args: &[String]) -> Result<Command, String> {
    // Check for help flag first
    if args.iter().any(|a| a == "--help" || a == "-h") {
        return Err("loct diff - Compare snapshots between branches/commits

USAGE:
    loct diff --since <SNAPSHOT> [--to <SNAPSHOT>] [OPTIONS]
    loct diff <SNAPSHOT1> [SNAPSHOT2]

OPTIONS:
    --since <SNAPSHOT>    Base snapshot to compare from (required)
    --to <SNAPSHOT>       Target snapshot to compare to (default: current working tree)
    --auto-scan-base      Automatically create git worktree and scan target branch
    --jsonl               Output in JSONL format (one change per line)
    --problems-only       Show only regressions (new dead code, new cycles)
    --help, -h            Show this help message

EXAMPLES:
    loct diff --since main
    loct diff --since HEAD~1"
            .to_string());
    }

    let mut opts = DiffOptions::default();
    let mut i = 0;

    while i < args.len() {
        let arg = &args[i];
        match arg.as_str() {
            "--since" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--since requires a snapshot ID or path".to_string())?;
                opts.since = Some(value.clone());
                i += 2;
            }
            "--to" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--to requires a snapshot ID or path".to_string())?;
                opts.to = Some(value.clone());
                i += 2;
            }
            "--auto-scan-base" => {
                opts.auto_scan_base = true;
                i += 1;
            }
            "--jsonl" => {
                opts.jsonl = true;
                i += 1;
            }
            "--problems-only" => {
                opts.problems_only = true;
                i += 1;
            }
            _ if !arg.starts_with('-') => {
                // First positional arg is --since value
                if opts.since.is_none() {
                    opts.since = Some(arg.clone());
                } else if opts.to.is_none() {
                    opts.to = Some(arg.clone());
                } else {
                    return Err(format!(
                        "Unexpected argument '{}'. diff takes at most two snapshot IDs.",
                        arg
                    ));
                }
                i += 1;
            }
            _ => {
                return Err(format!("Unknown option '{}' for 'diff' command.", arg));
            }
        }
    }

    if opts.since.is_none() {
        return Err(
            "'diff' command requires a snapshot ID to compare from.\nUsage: loct diff --since <snapshot-id> [--to <snapshot-id>]"
                .to_string(),
        );
    }

    Ok(Command::Diff(opts))
}

/// Parse `loct memex [options]` command - index analysis into AI memory.
pub(super) fn parse_memex_command(args: &[String]) -> Result<Command, String> {
    // Check for help flag first
    if args.iter().any(|a| a == "--help" || a == "-h") {
        return Err("loct memex - Index analysis into AI memory (vector DB)

USAGE:
    loct memex [REPORT_PATH] [OPTIONS]

OPTIONS:
    --report-path, -r <PATH>   Path to analysis report (JSON format)
    --project-id <ID>          Project identifier for multi-project databases
    --namespace, -n <NAME>     Namespace for embeddings (default: loctree)
    --db-path <PATH>           Custom vector DB path (default: ~/.rmcp_servers/rmcp_memex/lancedb)
    --help, -h                 Show this help message

EXAMPLES:
    loct memex report.json
    loct memex -r report.json --project-id vista"
            .to_string());
    }

    let mut opts = MemexOptions::default();
    let mut i = 0;

    while i < args.len() {
        let arg = &args[i];
        match arg.as_str() {
            "--report-path" | "-r" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--report-path requires a path".to_string())?;
                opts.report_path = PathBuf::from(value);
                i += 2;
            }
            "--project-id" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--project-id requires a value".to_string())?;
                opts.project_id = Some(value.clone());
                i += 2;
            }
            "--namespace" | "-n" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--namespace requires a value".to_string())?;
                opts.namespace = value.clone();
                i += 2;
            }
            "--db-path" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--db-path requires a path".to_string())?;
                opts.db_path = Some(value.clone());
                i += 2;
            }
            _ if !arg.starts_with('-') => {
                // Positional argument is report path
                opts.report_path = PathBuf::from(arg);
                i += 1;
            }
            _ => {
                return Err(format!("Unknown option '{}' for 'memex' command.", arg));
            }
        }
    }

    Ok(Command::Memex(opts))
}

/// Parse jq-style query command (e.g., `loct '.metadata'`).
pub(super) fn parse_jq_query_command(
    args: &[String],
    global: &GlobalOptions,
) -> Result<ParsedCommand, String> {
    if args.is_empty() {
        return Err("jq query requires a filter expression".to_string());
    }

    let mut opts = JqQueryOptions::default();

    // First arg should be the filter
    let mut i = if is_jq_filter(&args[0]) {
        opts.filter = args[0].clone();
        1
    } else {
        return Err(format!("Expected jq filter expression, got: '{}'", args[0]));
    };

    // Parse remaining jq-specific flags
    while i < args.len() {
        let arg = &args[i];
        match arg.as_str() {
            "-r" | "--raw-output" => {
                opts.raw_output = true;
                i += 1;
            }
            "-c" | "--compact-output" => {
                opts.compact_output = true;
                i += 1;
            }
            "-e" | "--exit-status" => {
                opts.exit_status = true;
                i += 1;
            }
            "--arg" => {
                let name = args
                    .get(i + 1)
                    .ok_or_else(|| "--arg requires a name and value".to_string())?;
                let value = args
                    .get(i + 2)
                    .ok_or_else(|| "--arg requires a name and value".to_string())?;
                opts.string_args.push((name.clone(), value.clone()));
                i += 3;
            }
            "--argjson" => {
                let name = args
                    .get(i + 1)
                    .ok_or_else(|| "--argjson requires a name and JSON value".to_string())?;
                let json_value = args
                    .get(i + 2)
                    .ok_or_else(|| "--argjson requires a name and JSON value".to_string())?;
                opts.json_args.push((name.clone(), json_value.clone()));
                i += 3;
            }
            "--snapshot" => {
                let path = args
                    .get(i + 1)
                    .ok_or_else(|| "--snapshot requires a path".to_string())?;
                opts.snapshot_path = Some(PathBuf::from(path));
                i += 2;
            }
            "--help" | "-h" => {
                return Ok(ParsedCommand::new(
                    Command::Help(HelpOptions {
                        command: Some("jq".to_string()),
                        ..Default::default()
                    }),
                    global.clone(),
                ));
            }
            _ => {
                return Err(format!("Unknown option '{}' for jq query mode", arg));
            }
        }
    }

    Ok(ParsedCommand::new(Command::JqQuery(opts), global.clone()))
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_info_command() {
        let args = vec!["src/".into()];
        let result = parse_info_command(&args).unwrap();
        if let Command::Info(opts) = result {
            assert_eq!(opts.root, Some(PathBuf::from("src/")));
        } else {
            panic!("Expected Info command");
        }
    }

    #[test]
    fn test_parse_lint_command() {
        let args = vec!["--fail".into(), "--tauri".into()];
        let result = parse_lint_command(&args).unwrap();
        if let Command::Lint(opts) = result {
            assert!(opts.fail);
            assert!(opts.tauri);
        } else {
            panic!("Expected Lint command");
        }
    }

    #[test]
    fn test_parse_report_command() {
        let args = vec!["--serve".into(), "--port".into(), "9000".into()];
        let result = parse_report_command(&args).unwrap();
        if let Command::Report(opts) = result {
            assert!(opts.serve);
            assert_eq!(opts.port, Some(9000));
        } else {
            panic!("Expected Report command");
        }
    }

    #[test]
    fn test_parse_report_command_rejects_format_flag() {
        let args = vec!["--format".into(), "json".into()];
        let err = parse_report_command(&args).expect_err("report should reject --format");
        assert!(err.contains("loct findings"));
    }

    #[test]
    fn test_parse_findings_command() {
        let args = vec!["--summary".into(), "src/".into()];
        let result = parse_findings_command(&args).unwrap();
        if let Command::Findings(opts) = result {
            assert!(opts.summary);
            assert_eq!(opts.roots, vec![PathBuf::from("src/")]);
        } else {
            panic!("Expected Findings command");
        }
    }

    #[test]
    fn test_parse_diff_command() {
        let args = vec!["--since".into(), "main".into()];
        let result = parse_diff_command(&args).unwrap();
        if let Command::Diff(opts) = result {
            assert_eq!(opts.since, Some("main".into()));
        } else {
            panic!("Expected Diff command");
        }
    }

    #[test]
    fn test_parse_jq_query_basic() {
        let global = GlobalOptions::default();
        let args = vec![".metadata".into()];
        let result = parse_jq_query_command(&args, &global).unwrap();
        if let Command::JqQuery(opts) = result.command {
            assert_eq!(opts.filter, ".metadata");
            assert!(!opts.raw_output);
            assert!(!opts.compact_output);
        } else {
            panic!("Expected JqQuery command");
        }
    }

    #[test]
    fn test_parse_jq_query_with_flags() {
        let global = GlobalOptions::default();
        let args = vec![".files[]".into(), "-r".into(), "-c".into()];
        let result = parse_jq_query_command(&args, &global).unwrap();
        if let Command::JqQuery(opts) = result.command {
            assert_eq!(opts.filter, ".files[]");
            assert!(opts.raw_output);
            assert!(opts.compact_output);
        } else {
            panic!("Expected JqQuery command");
        }
    }

    #[test]
    fn test_parse_jq_query_with_snapshot() {
        let global = GlobalOptions::default();
        let args = vec![
            ".metadata".into(),
            "--snapshot".into(),
            ".loctree/snap.json".into(),
        ];
        let result = parse_jq_query_command(&args, &global).unwrap();
        if let Command::JqQuery(opts) = result.command {
            assert_eq!(
                opts.snapshot_path,
                Some(PathBuf::from(".loctree/snap.json"))
            );
        } else {
            panic!("Expected JqQuery command");
        }
    }
}