trusty-search 0.3.68

Machine-wide hybrid code search service: BM25 + vector + KG, zero cold-start, MCP server
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
//! trusty-search CLI binary.
//!
//! Why: Single entry point that exposes both project-scoped commands
//! (`search`, `watch`, `status`, `init`, `add`, `remove`, `reindex`) which
//! auto-detect the index from the current working directory, and global
//! commands (`list`, `query`, `health`, `start`, `stop`, `serve`, `completions`)
//! that operate across the registry or manage the daemon.
//!
//! What: Parses CLI args via clap and dispatches to the per-subcommand
//! handlers in [`crate::commands`]. All implementation lives in those
//! modules; this file is purely a clap-to-handler shim plus a top-level
//! error printer.
//!
//! Test: `cargo run -- --help` → renders grouped command list with aliases.
//! `cargo run -- status` from inside this repo → prints `[trusty-search]`
//! detected via `.git`. `cargo test --workspace` → all tests pass.

mod commands;
mod detect;

// Re-export the library's modules into the binary's `crate::` namespace so
// existing `crate::core::*` / `crate::service::*` / `crate::mcp::*` imports
// in `commands/*.rs` resolve without churn after the workspace consolidation.
pub(crate) use trusty_search::{core, mcp, service};

use anyhow::Result;
use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
use clap_complete::{generate, Shell};
use colored::Colorize;
use commands::convert::ConvertTarget;
use commands::service::ServiceAction;
use std::io;

/// Machine-wide hybrid code search — BM25 + vector + knowledge graph.
///
/// Run from inside any project and trusty-search auto-detects the index.
/// Use `trusty-search start` to start the background service first.
#[derive(Parser)]
#[command(
    name = "trusty-search",
    version,
    author,
    propagate_version = true,
    subcommand_required = true,
    arg_required_else_help = true
)]
struct Cli {
    /// Override the auto-detected project index
    #[arg(short = 'i', long, global = true, env = "TRUSTY_INDEX")]
    index: Option<String>,

    /// Output results as JSON
    #[arg(long, global = true)]
    json: bool,

    /// Enable debug logging
    #[arg(short, long, global = true)]
    verbose: bool,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    // ── Project commands (auto-detect index from CWD) ──────────────────────
    /// Hybrid search in current project  [alias: s]
    ///
    /// Examples:
    ///   trusty-search search "fn authenticate"
    ///   trusty-search search "error handling" --intent conceptual
    ///   trusty-search search "TODO FIXME" --intent bugdebt --top-k 20
    #[command(alias = "s", display_order = 1)]
    Search {
        /// Search query (natural language or code)
        query: String,

        /// Number of results to return
        #[arg(short = 'k', long, default_value = "10")]
        top_k: usize,

        /// Show full chunk content instead of compact snippet
        #[arg(short, long)]
        full: bool,

        /// Force query intent classification
        #[arg(long, value_enum)]
        intent: Option<IntentArg>,

        /// Skip knowledge graph expansion
        #[arg(long)]
        no_kg: bool,

        /// Pagination offset
        #[arg(long, default_value = "0")]
        offset: usize,

        /// Max token budget for results
        #[arg(long, default_value = "8000")]
        budget: u32,
    },

    /// Watch for changes and keep index updated  [alias: w]
    ///
    /// Examples:
    ///   trusty-search watch
    ///   trusty-search watch ~/Projects/myapp
    #[command(alias = "w", display_order = 2)]
    Watch {
        /// Directory to watch (default: auto-detected project root)
        path: Option<std::path::PathBuf>,
    },

    /// Show daemon status and all index stats  [alias: st]
    ///
    /// Shows daemon liveness, version, and per-index chunk counts.
    /// `health` produces the same output (kept for backward compatibility).
    ///
    /// Examples:
    ///   trusty-search status
    ///   trusty-search status --json
    #[command(alias = "st", display_order = 3)]
    Status,

    /// Register and index a project in one step  [alias: idx]
    ///
    /// Registers the index with the daemon if needed, then runs a reindex
    /// with a live progress bar. Skips the reindex if the index already has
    /// chunks indexed (use --force to override).
    ///
    /// When run with no PATH argument, trusty-search looks for a
    /// `.trusty-search.yaml` file in the current directory and uses its
    /// `name`, `path`, and `exclude` values as defaults. CLI flags always
    /// override the config file. (For multi-index polyrepos, use the separate
    /// `trusty-search.yaml` manifest — no leading dot.)
    ///
    /// Examples:
    ///   trusty-search index                   # CWD, name from basename or .trusty-search.yaml
    ///   trusty-search index ~/Projects/myapp
    ///   trusty-search index --force           # full reindex even if up-to-date
    ///   trusty-search index --exclude data/ --exclude "*.db"
    #[command(alias = "idx", display_order = 4)]
    Index {
        /// Directory to register and index (default: CWD, or `.trusty-search.yaml` `path`)
        path: Option<std::path::PathBuf>,

        /// Index name (default: directory basename, or `.trusty-search.yaml` `name`)
        #[arg(short, long)]
        name: Option<String>,

        /// Force a full reindex even if the index already has chunks
        #[arg(short, long)]
        force: bool,

        /// Additional glob exclusion patterns (override `.trusty-search.yaml` `exclude`)
        #[arg(long)]
        exclude: Vec<String>,

        /// SSE stream timeout in seconds (default: 600). Increase for very large repos.
        #[arg(long, default_value_t = 600)]
        timeout: u64,
    },

    /// Register current directory as a named index (see `index`)
    ///
    /// Kept for backward compatibility. Prefer `trusty-search index`, which
    /// registers AND indexes in one step.
    ///
    /// Examples:
    ///   trusty-search init
    ///   trusty-search init ~/Projects/myapp --name myapp-prod
    #[command(alias = "i", display_order = 4)]
    Init {
        /// Directory to register (default: CWD)
        path: Option<std::path::PathBuf>,

        /// Index name (default: directory basename)
        #[arg(short, long)]
        name: Option<String>,

        /// Additional glob exclusion patterns
        #[arg(long)]
        exclude: Vec<String>,
    },

    /// Add or update a single file in the index
    ///
    /// Examples:
    ///   trusty-search add src/main.rs
    #[command(display_order = 5)]
    Add {
        /// File to index
        file: std::path::PathBuf,
    },

    /// Remove a file from the index  [alias: rm]
    ///
    /// Examples:
    ///   trusty-search remove src/old.rs
    #[command(alias = "rm", display_order = 6)]
    Remove {
        /// File to remove
        file: std::path::PathBuf,
    },

    /// Full reindex of current project (see `index --force`)
    ///
    /// Streams progress via SSE and renders a live progress bar. Prefer
    /// `trusty-search index --force` which also handles registration.
    ///
    /// Examples:
    ///   trusty-search reindex
    ///   trusty-search reindex ~/Projects/myapp
    #[command(display_order = 7)]
    Reindex {
        /// Directory to reindex (default: auto-detected project root)
        path: Option<std::path::PathBuf>,

        /// SSE stream timeout in seconds (default: 600). Increase for very large repos.
        #[arg(long, default_value_t = 600)]
        timeout: u64,
    },

    // ── Global / multi-index commands ─────────────────────────────────────
    /// List all registered indexes with stats  [alias: ls]
    ///
    /// Examples:
    ///   trusty-search list
    ///   trusty-search list --json
    #[command(alias = "ls", display_order = 10)]
    List,

    /// Search across all or named indexes  [alias: q]
    ///
    /// Examples:
    ///   trusty-search query "fn authenticate" --indexes "*"
    ///   trusty-search query "database pool" --indexes proj-a,proj-b
    #[command(alias = "q", display_order = 11)]
    Query {
        /// Search query
        query: String,

        /// Indexes to search: "*" for all, or comma-separated names
        #[arg(long, default_value = "*")]
        indexes: String,

        /// Number of results
        #[arg(short = 'k', long, default_value = "10")]
        top_k: usize,

        /// Show full chunk content
        #[arg(short, long)]
        full: bool,
    },

    /// Check daemon liveness (alias for `status`)
    ///
    /// Kept for backward compatibility. Both `health` and `status` produce
    /// the same rich output: daemon URL, version, and per-index chunk counts.
    ///
    /// Examples:
    ///   trusty-search health
    #[command(display_order = 12)]
    Health,

    // ── Service commands ──────────────────────────────────────────────────
    /// Start the HTTP daemon
    ///
    /// By default, self-spawns a detached background copy of itself (with
    /// `--foreground`) and returns immediately, so the daemon survives the
    /// caller's terminal closing (e.g. tmux pane SIGHUP, `make patch`).
    /// Use `--foreground` when the process is supervised by launchd, systemd,
    /// or Docker — those supervisors require the managed binary to stay in
    /// the foreground rather than forking.
    ///
    /// Examples:
    ///   trusty-search start
    ///   trusty-search start --port 7878
    ///   trusty-search start --foreground --port 7878   # launchd / systemd
    #[command(display_order = 20)]
    Start {
        /// Port to listen on (default: 7878, auto-selects next if busy)
        #[arg(long, default_value_t = trusty_search::service::DEFAULT_PORT)]
        port: u16,

        /// Run in the foreground instead of forking a background daemon.
        ///
        /// Default (`trusty-search start`): self-spawns a detached child with
        /// `--foreground` and returns immediately, so the daemon survives the
        /// caller's terminal closing (e.g. tmux pane SIGHUP). Use this flag
        /// when the process is managed by launchd, systemd, or Docker — those
        /// supervisors require the managed binary to stay in the foreground.
        #[arg(long, default_value_t = false)]
        foreground: bool,

        /// Embedding execution device: `auto` (default), `cpu`, or `gpu`.
        ///
        /// - `auto`: prefer CUDA on Linux/Windows (binary must be built with
        ///   `--features cuda`), then CoreML on Apple Silicon, otherwise CPU.
        /// - `cpu`: force CPU even when a GPU is available — useful for A/B
        ///   benchmarking or freeing the GPU for another workload.
        /// - `gpu`: require GPU acceleration; exit 1 if no GPU EP can be
        ///   initialised. Useful on a dedicated GPU indexing node where
        ///   silent CPU fallback would mean a 10× slower reindex.
        ///
        /// Implemented as the `TRUSTY_DEVICE` env var, which the embedder
        /// reads at session-init time. Set explicitly to override the daemon
        /// default.
        #[arg(long, value_parser = ["auto", "cpu", "gpu"], default_value = "auto")]
        device: String,
    },

    /// Stop the running background daemon
    ///
    /// Sends SIGTERM to the daemon process and waits for clean shutdown.
    ///
    /// Examples:
    ///   trusty-search stop
    #[command(display_order = 21)]
    Stop,

    /// Start MCP server (stdio by default; add --with-http for an HTTP listener)
    ///
    /// Stdio MCP is always served on the process's stdin/stdout for Claude
    /// Code, which pipes JSON-RPC directly and needs nothing more — so the
    /// HTTP listener is OFF by default (issue #123).
    ///
    /// Pass `--with-http` to additionally bind an HTTP/SSE transport on
    /// 127.0.0.1:<port> (port 0 = OS-chosen free port). The bound address is
    /// written to `~/.trusty-search/mcp_http_addr` so admin clients can
    /// discover it.
    ///
    /// Examples:
    ///   trusty-search serve                       # MCP stdio only (Claude hook)
    ///   trusty-search serve --with-http           # MCP stdio + HTTP on :0
    ///   trusty-search serve --with-http --port 7878  # MCP stdio + HTTP on :7878
    ///   trusty-search serve --http 0.0.0.0:8080   # legacy: explicit bind addr
    ///
    /// `--no-http` is accepted but ignored — HTTP is already off by default.
    #[command(display_order = 22)]
    Serve {
        /// Enable the HTTP/SSE listener in addition to MCP stdio.
        ///
        /// Off by default: Claude Code MCP hooks pipe JSON-RPC over
        /// stdin/stdout and never need the HTTP admin panel, so binding it
        /// would just waste a port. Opt in with this flag when you want the
        /// HTTP transport (e.g. for the browser admin panel).
        #[arg(long, default_value_t = false)]
        with_http: bool,

        /// Deprecated no-op: HTTP is now OFF by default (issue #123), so
        /// `--no-http` does nothing. Kept as a hidden, accepted flag so
        /// existing `.mcp.json` configs that still pass it don't break.
        #[arg(long, hide = true, default_value_t = false)]
        no_http: bool,

        /// Port for the HTTP/SSE MCP transport (default: 0 = OS picks).
        ///
        /// Only used when `--with-http` is set.
        #[arg(long, default_value_t = 0)]
        port: u16,

        /// Legacy: explicit "host:port" bind address. When set, overrides
        /// `--port`. Kept for backward compatibility with older docs.
        #[arg(long)]
        http: Option<String>,
    },

    /// Manage the macOS launchd service (install/uninstall/status/logs)
    ///
    /// Installs a LaunchAgent plist at
    /// `~/Library/LaunchAgents/com.trusty.trusty-search.plist` that runs the
    /// daemon in the foreground under launchd supervision. Not supported on
    /// Linux / Windows — the subcommand exits 1 with a clear message.
    ///
    /// Examples:
    ///   trusty-search service install
    ///   trusty-search service status
    ///   trusty-search service logs
    ///   trusty-search service uninstall
    #[command(display_order = 24)]
    Service {
        #[command(subcommand)]
        action: ServiceAction,
    },

    /// Open the admin panel of the running daemon in the default browser
    ///
    /// Reads `~/.trusty-search/http_addr` to discover the daemon, then opens
    /// `http://<addr>/ui` in the default browser. Falls back to printing the
    /// URL if the browser fails to launch. Errors clearly if no daemon is
    /// running (no discovery file).
    ///
    /// Examples:
    ///   trusty-search dashboard
    ///   trusty-search dash
    ///   trusty-search ui
    #[command(display_order = 23, aliases = ["dash", "ui"])]
    Dashboard,

    /// Migrate mcp-vector-search project(s) to trusty-search
    ///
    /// Reads `.mcp-vector-search/config.json` from each project, derives an
    /// index name from the project root's basename, and POSTs to the daemon
    /// to create + reindex the project.
    ///
    /// Examples:
    ///   trusty-search convert project           # convert current project
    ///   trusty-search convert all               # convert every project on this machine
    ///   trusty-search convert all --dry-run     # preview without changes
    #[command(display_order = 25)]
    Convert {
        /// What to convert: "project" (CWD) or "all" (machine-wide scan)
        #[arg(value_name = "TARGET")]
        target: ConvertTarget,

        /// Show what would be converted without contacting the daemon
        #[arg(long)]
        dry_run: bool,

        /// Maximum concurrent conversions for "all"
        #[arg(long, default_value = "4")]
        concurrency: usize,
    },

    /// Migrate from mcp-vector-search (or other tools) to trusty-search
    ///
    /// Updates Claude MCP configuration files and migrates project indexes.
    ///
    /// Examples:
    ///   trusty-search migrate mcp-vector-search           # migrate both MCP config + indexes
    ///   trusty-search migrate mcp-vector-search --dry-run # preview changes
    ///   trusty-search migrate mcp-vector-search --mcp-only
    ///   trusty-search migrate mcp-vector-search --indexes-only
    #[command(display_order = 26)]
    Migrate {
        /// Migration source: "mcp-vector-search"
        #[arg(value_name = "FROM")]
        target: commands::migrate::MigrateTarget,

        /// Preview changes without modifying any files or contacting the daemon
        #[arg(long)]
        dry_run: bool,

        /// Only update Claude MCP config files; skip index migration
        #[arg(long, conflicts_with = "indexes_only")]
        mcp_only: bool,

        /// Only migrate indexes; skip MCP config file updates
        #[arg(long, conflicts_with = "mcp_only")]
        indexes_only: bool,
    },

    /// Wire trusty-search into an IDE (Cursor, etc.)
    ///
    /// Writes MCP server config and AI rules files for the target IDE.
    /// No daemon required — this command only writes config files.
    ///
    /// Examples:
    ///   trusty-search integrate cursor                 # global + project MCP config + rules
    ///   trusty-search integrate cursor --dry-run       # preview without writing
    ///   trusty-search integrate cursor --global-only   # only ~/.cursor/mcp.json
    ///   trusty-search integrate cursor --no-rules      # MCP config only, skip rules file
    #[command(display_order = 27)]
    Integrate {
        /// IDE to integrate with: "cursor"
        #[arg(value_name = "IDE")]
        target: commands::integrate::IntegrateTarget,

        /// Preview changes without writing any files
        #[arg(long)]
        dry_run: bool,

        /// Only update the global IDE config (~/.cursor/mcp.json); skip project files
        #[arg(long, conflicts_with = "project_only")]
        global_only: bool,

        /// Only update project-level files (.cursor/mcp.json + rules); skip global config
        #[arg(long, conflicts_with = "global_only")]
        project_only: bool,

        /// Skip writing the .cursor/rules/trusty-search.mdc rules file
        #[arg(long)]
        no_rules: bool,
    },

    /// Diagnose configuration, model cache, and index health
    ///
    /// Checks each component and reports ✓ / ✗ / ⚠ for each. Exit code 0
    /// when all checks pass or only warnings; exit code 1 when any error is
    /// found. Pass --fix to attempt automatic repair of fixable problems.
    ///
    /// Examples:
    ///   trusty-search doctor
    ///   trusty-search doctor --fix
    #[command(display_order = 28)]
    Doctor {
        /// Attempt to fix detected problems automatically
        #[arg(long)]
        fix: bool,
    },

    /// Get or set runtime daemon configuration (memory limits)
    ///
    /// Updates take effect immediately on the running daemon — no restart
    /// required. Use `0`, `off`, `none`, `disable`, or `unlimited` as the
    /// value to remove a limit.
    ///
    /// Examples:
    ///   trusty-search config get
    ///   trusty-search config get memory-limit
    ///   trusty-search config set memory-limit 16384
    ///   trusty-search config set index-memory-limit 65536
    ///   trusty-search config set memory-limit off
    #[command(display_order = 29)]
    Config {
        #[command(subcommand)]
        action: commands::config::ConfigAction,
    },

    /// Monitor the trusty-search daemon via web UI or terminal dashboard
    ///
    /// `monitor web` prints the admin panel URL of the running daemon (and
    /// attempts to open it in the default browser). `monitor tui` launches the
    /// trusty-search-specific ratatui dashboard: an index list, a live
    /// reindex/search activity log, and a query bar.
    ///
    /// Examples:
    ///   trusty-search monitor web
    ///   trusty-search monitor tui
    #[command(display_order = 30, subcommand_required = true)]
    Monitor {
        #[command(subcommand)]
        target: MonitorTarget,
    },

    /// Generate shell completion script
    ///
    /// Examples:
    ///   trusty-search completions zsh > ~/.zsh/completions/_trusty-search
    ///   trusty-search completions bash >> ~/.bashrc
    #[command(display_order = 31)]
    Completions {
        /// Shell to generate completions for
        #[arg(value_enum)]
        shell: Shell,
    },
}

/// Target surface for the `monitor` subcommand.
///
/// Why: operators want a quick browser link to the daemon's admin panel, the
/// trusty-search-specific terminal dashboard, OR the same dashboard data as
/// plain text / JSON so scripts and CI can read it without a TUI (issues #33,
/// #34).
/// What: `Web` prints (and opens) the daemon's `/ui` URL; `Tui` launches the
/// trusty-search-specific `trusty_common::monitor::search_tui` ratatui
/// dashboard; `Status` and `Indexes` print scriptable health and per-index
/// stats.
/// Test: `cargo run -p trusty-search -- monitor --help` lists every variant.
#[derive(Subcommand)]
enum MonitorTarget {
    /// Open the web dashboard URL in the terminal (or browser)
    Web,
    /// Launch the trusty-search terminal UI: indexes, reindex, and search monitor
    Tui,
    /// Print daemon status: health, version, uptime, and corpus totals
    ///
    /// Examples:
    ///   trusty-search monitor status
    ///   trusty-search monitor status --json
    Status {
        /// Emit the status as a JSON object instead of plain text
        #[arg(long)]
        json: bool,
    },
    /// List every index, or show one index's detail when an ID is given
    ///
    /// Examples:
    ///   trusty-search monitor indexes
    ///   trusty-search monitor indexes my-project
    ///   trusty-search monitor indexes --json
    Indexes {
        /// Optional index ID to show detail for (omit to list all)
        id: Option<String>,
        /// Emit the result as JSON instead of a plain-text table
        #[arg(long)]
        json: bool,
    },
}

/// Why: Allow users to override `QueryClassifier`'s automatic intent detection
/// when they know the intent up-front (e.g. searching for TODO comments).
/// What: Mirrors `crate::core::QueryIntent` for the CLI surface.
/// Test: `cargo run -- search foo --intent conceptual --help` parses without error.
#[derive(Debug, Clone, ValueEnum)]
enum IntentArg {
    Definition,
    Usage,
    Conceptual,
    Bugdebt,
    Unknown,
}

#[tokio::main]
async fn main() {
    // Central error-printer + exit-code chooser. Why: command handlers are now
    // testable units that return `Result<()>` instead of calling `process::exit`
    // directly (issue #104). Print the chain compactly with the red ✗ prefix
    // operators already recognize, then exit 1.
    if let Err(e) = run().await {
        let msg = format!("{:#}", e);
        if !msg.is_empty() {
            eprintln!("{} {}", "".red(), msg);
        }
        std::process::exit(1);
    }
}

async fn run() -> Result<()> {
    dotenvy::from_filename(".env.local").ok();

    let cli = Cli::parse();

    // Tracing init + NO_COLOR handling via shared trusty-common helpers.
    //
    // The `start` daemon command initialises tracing itself via
    // `init_tracing_with_buffer` so it can wire the in-memory `LogBuffer`
    // that backs `GET /logs/tail` (issue #35). Installing a plain subscriber
    // here would win the `try_init` race and leave that buffer empty, so we
    // skip the early init for `start` only.
    if !matches!(cli.command, Commands::Start { .. }) {
        trusty_common::init_tracing(if cli.verbose { 2 } else { 0 });
    }
    trusty_common::maybe_disable_color(false);

    match cli.command {
        Commands::Search {
            query,
            top_k,
            full: _,
            intent: _,
            no_kg: _,
            offset: _,
            budget: _,
        } => {
            commands::search::handle_search(&cli.index, query, top_k).await?;
        }

        Commands::Watch { path } => {
            commands::watch::handle_watch(&cli.index, path).await?;
        }

        Commands::Status => {
            commands::status::handle_status(cli.json).await?;
        }

        Commands::Init {
            path,
            name,
            exclude,
        } => {
            commands::init::handle_init(path, name, exclude).await?;
        }

        Commands::Index {
            path,
            name,
            force,
            exclude,
            timeout,
        } => {
            commands::index::handle_index(path, name, force, exclude, timeout).await?;
        }

        Commands::Add { file } => {
            commands::add::handle_add(&cli.index, file).await?;
        }

        Commands::Remove { file } => {
            commands::remove::handle_remove(&cli.index, file).await?;
        }

        Commands::Reindex { path, timeout } => {
            commands::reindex::handle_reindex(&cli.index, path, timeout).await?;
        }

        Commands::List => {
            commands::list::handle_list(cli.json).await?;
        }

        Commands::Query {
            query,
            indexes,
            top_k,
            full,
        } => {
            commands::query::handle_query(&cli.index, cli.json, query, indexes, top_k, full)
                .await?;
        }

        // `health` is an alias registered on the `status` subcommand, so
        // this arm catches the bare `Commands::Health` variant which is kept
        // for backward-compat with any scripts that invoke it directly.
        Commands::Health => {
            commands::status::handle_status(cli.json).await?;
        }

        Commands::Start {
            port,
            foreground,
            device,
        } => {
            commands::start::handle_start(port, foreground, &device, cli.verbose).await?;
        }

        Commands::Stop => {
            commands::stop::handle_stop().await?;
        }

        Commands::Serve {
            with_http,
            no_http: _, // deprecated no-op (issue #123): HTTP is opt-in now
            port,
            http,
        } => {
            commands::serve::handle_serve(with_http, port, http).await?;
        }

        Commands::Service { action } => {
            commands::service::handle_service(&action)?;
        }

        Commands::Dashboard => {
            commands::dashboard::handle_dashboard().await?;
        }

        Commands::Convert {
            target,
            dry_run,
            concurrency,
        } => {
            commands::convert::handle_convert(target, dry_run, concurrency).await?;
        }

        Commands::Migrate {
            target,
            dry_run,
            mcp_only,
            indexes_only,
        } => {
            commands::migrate::handle_migrate(target, dry_run, mcp_only, indexes_only).await?;
        }

        Commands::Integrate {
            target,
            dry_run,
            global_only,
            project_only,
            no_rules,
        } => {
            commands::integrate::handle_integrate(
                target,
                dry_run,
                global_only,
                project_only,
                no_rules,
            )
            .await?;
        }

        Commands::Doctor { fix } => {
            commands::doctor::handle_doctor(fix).await?;
        }

        Commands::Config { action } => {
            commands::config::handle_config(action).await?;
        }

        Commands::Monitor { target } => match target {
            MonitorTarget::Web => {
                // Prefer the live address written by a running daemon; fall
                // back to the default loopback port so the command still
                // prints something useful when the daemon has not started.
                let url = match trusty_common::read_daemon_addr("trusty-search") {
                    Ok(Some(addr)) => format!("{addr}/ui"),
                    _ => format!(
                        "http://127.0.0.1:{}/ui",
                        trusty_search::service::DEFAULT_PORT
                    ),
                };
                println!("{url}");
                open::that(&url).ok();
            }
            MonitorTarget::Tui => {
                trusty_common::monitor::search_tui::run().await?;
            }
            MonitorTarget::Status { json } => {
                commands::monitor::handle_status(json).await?;
            }
            MonitorTarget::Indexes { id, json } => {
                commands::monitor::handle_indexes(id, json).await?;
            }
        },

        Commands::Completions { shell } => {
            let mut cmd = Cli::command();
            let name = cmd.get_name().to_string();
            generate(shell, &mut cmd, name, &mut io::stdout());
        }
    }

    Ok(())
}