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
//! # loctree
//!
//! **AI-oriented Project Analyzer** - Static analysis tool designed for AI agents
//! and developers building production-ready software.
//!
//! loctree helps overcome the common AI tendency to generate excessive artifacts
//! that lead to re-export cascades, circular imports, and spaghetti dependencies.
//!
//! ## Features
//!
//! - **Holographic Slice** - Extract focused context (deps + consumers) for any file
//! - **Handler Trace** - Follow Tauri commands through the entire pipeline
//! - **Dead Export Detection** - Find unused exports and orphaned code
//! - **Circular Import Detection** - Catch runtime bombs before they explode
//! - **Auto-Detect Stack** - Automatically configure for Rust, TypeScript, Python, Tauri
//! - **HTML Reports** - Interactive reports with Cytoscape.js dependency graphs
//!
//! ## Quick Start (Library Usage)
//!
//! ```rust,no_run
//! use loctree::{detect, snapshot, slicer};
//! use std::path::PathBuf;
//!
//! // Detect project stack
//! let detected = detect::detect_stack(std::path::Path::new("."));
//! println!("Detected: {}", detected.description);
//! ```
//!
//! ## Running Import Analysis
//!
//! ```rust,no_run
//! use loctree::{analyzer, args};
//! use std::path::PathBuf;
//!
//! // Run the full import analyzer on a project
//! let mut parsed = args::ParsedArgs::default();
//! parsed.dead_exports = true;
//! parsed.circular = true;
//!
//! let roots = vec![PathBuf::from(".")];
//! analyzer::run_import_analyzer(&roots, &parsed).unwrap();
//! ```
//!
//! ## CLI Usage
//!
//! For command-line usage, install with `cargo install loctree` and run:
//!
//! ```bash
//! loctree # Scan and snapshot
//! loctree slice src/App.tsx # Extract AI context
//! loctree trace get_user # Trace Tauri handler
//! loctree -A --circular # Find circular imports
//! loctree --for-ai # AI-optimized JSON output
//! ```
//!
//! See the [README](https://github.com/Loctree/Loctree) for full documentation.
// ============================================================================
// Core Modules
// ============================================================================
/// Import/export analyzer supporting TypeScript, JavaScript, Python, Rust, and CSS.
///
/// # Submodules
///
/// - [`analyzer::js`] - TypeScript/JavaScript analysis
/// - [`analyzer::py`] - Python analysis
/// - [`analyzer::rust`] - Rust analysis (Tauri commands)
/// - [`analyzer::cycles`] - Circular import detection (Tarjan's SCC)
/// - [`analyzer::dead_parrots`] - Dead export detection
/// - [`analyzer::trace`] - Handler tracing for Tauri
/// - [`analyzer::coverage`] - Tauri command coverage
/// - [`analyzer::for_ai`] - AI-optimized output generation
/// - [`analyzer::html`] - HTML report generation
/// - [`analyzer::sarif`] - SARIF 2.1.0 output for CI
/// New CLI module for the subcommand-based interface.
///
/// Provides the canonical `loct <command> [options]` interface with:
/// - [`Command`](cli::Command) enum as the source of truth for all commands
/// - [`GlobalOptions`](cli::GlobalOptions) for shared flags
/// - Per-command option structs
/// - Legacy adapter for backward compatibility (until v1.0)
///
/// # Key Commands (Human Interface)
///
/// - `loct` / `loct auto` - Full auto-scan with stack detection (default)
/// - `loct scan` - Build/update snapshot
/// - `loct dead` - Detect unused exports
/// - `loct commands` - Show Tauri command bridges
/// - `loct events` - Show event flow
/// - `loct slice <path>` - Extract holographic context
///
/// # Agent Interface
///
/// Agents should use `--json` output with regex filters on metadata:
/// - `loct find --symbol '.*patient.*' --lang ts --json`
/// - `loct dead --confidence high --json`
/// Command-line argument parsing.
///
/// Contains [`ParsedArgs`](args::ParsedArgs) struct and [`parse_args`](args::parse_args) function.
/// Configuration file support.
///
/// Loads `.loctree/config.toml` for project-specific settings like custom Tauri command macros.
/// Suppression system for false positives.
///
/// Allows marking findings as "reviewed and OK" so they don't appear in subsequent runs.
/// Stored in `.loctree/suppressions.toml`.
/// Auto-detection of project stacks.
///
/// Detects Rust, TypeScript, Python, Tauri, Vite, and more based on marker files.
///
/// # Example
///
/// ```rust,no_run
/// use loctree::detect;
/// use std::path::Path;
///
/// let detected = detect::detect_stack(Path::new("."));
/// if !detected.is_empty() {
/// println!("Stack: {}", detected.description);
/// println!("Extensions: {:?}", detected.extensions);
/// }
/// ```
/// Filesystem utilities.
///
/// - Gitignore handling with [`GitIgnoreChecker`](fs_utils::GitIgnoreChecker)
/// - File gathering with extension/depth filters
/// - Line counting
/// - Pattern normalization
/// String similarity using Levenshtein distance.
///
/// Used for fuzzy matching in `--check` mode to find similar component names.
/// Holographic slice extraction.
///
/// Extracts a file's context in three layers:
/// - **Core** - The target file itself
/// - **Deps** - Files the target imports (transitive)
/// - **Consumers** - Files that import the target
///
/// # Example
///
/// ```rust,no_run
/// use loctree::slicer;
/// use loctree::args::ParsedArgs;
/// use std::path::Path;
///
/// let parsed = ParsedArgs::default();
/// let root = Path::new(".");
///
/// // Extract slice for src/App.tsx with consumers, as JSON
/// slicer::run_slice(root, "src/App.tsx", true, true, &parsed).unwrap();
/// ```
/// Directory-level holographic focus.
///
/// Like slicer but for directories instead of single files.
/// CSS Layout Analysis.
///
/// Scans CSS/SCSS files for layout-related properties:
/// z-index, position: sticky/fixed, display: grid/flex.
/// Incremental snapshot persistence.
///
/// Saves analysis results to cached artifacts for faster subsequent runs.
/// By default, artifacts live in the OS user cache dir (override via `LOCT_CACHE_DIR`).
/// Uses file modification times to skip unchanged files.
///
/// # Key Types
///
/// - [`Snapshot`](snapshot::Snapshot) - The persisted analysis state
/// - [`SnapshotMetadata`](snapshot::SnapshotMetadata) - Version and timestamp info
/// - [`GraphEdge`](snapshot::GraphEdge) - Import relationship
/// - [`CommandBridge`](snapshot::CommandBridge) - FE→BE command mapping
/// Directory tree with LOC counts.
///
/// Fast tree view similar to Unix `tree` command but with:
/// - Line counts per file
/// - Large file highlighting
/// - Gitignore support
/// - Build artifact detection (`--find-artifacts`)
/// Common types used throughout the crate.
///
/// # Key Types
///
/// - [`Mode`] - CLI mode (Tree, Slice, Trace, AnalyzeImports, ForAi, Git)
/// - [`Options`] - Analysis configuration
/// - [`FileAnalysis`] - Per-file analysis result
/// - `ImportEntry` - Import statement representation
/// - `ExportSymbol` - Export declaration
/// - `CommandRef` - Tauri command reference
/// Terminal color utilities for CLI output.
///
/// Provides ANSI color codes and semantic helpers for consistent
/// colorized output across all loctree commands.
///
/// # Key Types
///
/// - [`Painter`](colors::Painter) - Color-aware string formatter
/// - [`is_enabled`](colors::is_enabled) - Color mode detection
/// Git operations for temporal awareness.
///
/// Native git operations using libgit2 for analyzing repository history.
///
/// # Key Types
///
/// - [`GitRepo`](git::GitRepo) - Git repository wrapper
/// - [`CommitInfo`](git::CommitInfo) - Commit metadata
/// - [`ChangedFile`](git::ChangedFile) - File change between commits
///
/// # Example
///
/// ```rust,no_run
/// use loctree::git::GitRepo;
/// use std::path::Path;
///
/// let repo = GitRepo::discover(Path::new(".")).unwrap();
/// let head = repo.head_commit().unwrap();
/// println!("HEAD: {}", head);
/// ```
/// Snapshot comparison engine for temporal analysis.
///
/// Compares loctree snapshots between commits to show semantic changes.
///
/// # Key Types
///
/// - [`SnapshotDiff`](diff::SnapshotDiff) - Result of comparing two snapshots
/// - [`GraphDiff`](diff::GraphDiff) - Import graph changes
/// - [`ExportsDiff`](diff::ExportsDiff) - Export changes
/// - [`DeadCodeDiff`](diff::DeadCodeDiff) - Dead code changes
/// - [`ImpactAnalysis`](diff::ImpactAnalysis) - Change impact assessment
/// Query API for fast lookups against the cached snapshot.
///
/// Provides interactive queries without re-scanning:
/// - `who-imports <file>` - Find all files that import a given file
/// - `where-symbol <symbol>` - Find where a symbol is defined
/// - `component-of <file>` - Show what component/module a file belongs to
///
/// # Example
///
/// ```rust,no_run
/// use loctree::{query, snapshot};
/// use std::path::Path;
///
/// let snapshot = snapshot::Snapshot::load(Path::new(".")).unwrap();
/// let result = query::query_who_imports(&snapshot, "src/utils.ts");
/// println!("Found {} importers", result.results.len());
/// ```
/// Memex module for AI agent context management.
///
/// Provides semantic codebase exploration and context extraction for AI agents.
/// Requires the `memex` feature flag (heavy dependencies).
/// Progress UI utilities (spinners, status messages).
///
/// Provides Black-style visual feedback for CLI operations.
/// jaq query execution for filtering snapshot data.
///
/// Provides jq-compatible filtering using the jaq library.
/// Impact analysis module for understanding file dependencies.
///
/// Analyzes "what breaks if you modify/remove this file" by traversing
/// the reverse dependency graph to find all direct and transitive consumers.
/// Watch mode for live snapshot refresh during iterative development.
///
/// Provides file system watching with debouncing and incremental re-scanning.
/// Refactor plan generation for architectural reorganization.
///
/// Analyzes module coupling and suggests safe file reorganization:
/// - Layer detection (UI, App, Kernel, Infra)
/// - Risk scoring based on consumer count and file size
/// - Topological ordering for safe incremental moves
/// - Shim generation for backward compatibility
// ============================================================================
// Re-exports for convenience
// ============================================================================
/// CLI modes.
pub use Mode;
/// Analysis options.
pub use Options;
/// Output format (Text, Json, Jsonl).
pub use OutputMode;
/// Color mode (Auto, Always, Never).
pub use ColorMode;
/// Per-file analysis result with imports, exports, commands, etc.
pub use FileAnalysis;
/// Detected project stack with extensions and ignores.
pub use DetectedStack;
/// Main stack detection function.
pub use detect_stack;
/// Holographic slice result.
pub use HolographicSlice;
/// Slice configuration.
pub use SliceConfig;
/// Persisted analysis state.
pub use Snapshot;
/// Run the import analyzer.
pub use run_import_analyzer;
/// Report section for HTML output.
pub use ReportSection;
/// Command gap (missing/unused handler).
pub use CommandGap;
/// Ranked duplicate export.
pub use RankedDup;
/// Refactor plan result.
pub use RefactorPlan;
/// Architectural layer classification.
pub use Layer;
/// Risk level for refactor operations.
pub use RiskLevel;
// ============================================================================
// CLI types (new subcommand interface)
// ============================================================================
/// CLI command enum (source of truth for `loct <command>`).
pub use Command;
/// Global CLI options (--json, --quiet, --verbose, --color).
pub use GlobalOptions;
/// Parsed command result with deprecation warning support.
pub use ParsedCommand;