amql-cli 0.0.0-alpha.0

AQL command-line interface and REPL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
//! AQL command-line interface and interactive REPL.

mod messages;
mod repl;

use amql_engine::{
    diff_annotations, execute_bench_request, execute_transaction, extract_aql_symbols,
    find_project_root, format_bench_table, init_project, insert as nav_insert, load_manifest, meta,
    nav_select, project_stats, read_source, remove as nav_remove, replace as nav_replace,
    run_all_extractors, sidecar_for_colocated, suggest_repairs, unified_query, validate,
    AnnotationStore, AqlDef, BaselineDef, BenchRequest, CodeCache, ExtractorRegistry,
    InsertPosition, NodeRef, ProjectRoot, QueryOptions, RelativePath, ResolverRegistry, Scope,
    TransactionOp,
};
use amql_log::{debug, info};
use clap::{CommandFactory, FromArgMatches, Parser, Subcommand};
use rmcp::ServiceExt;
use std::path::PathBuf;
use std::process::ExitCode;

#[derive(Parser)]
// name and about are set at runtime from amql_engine::meta and the message catalog.
// Future: migrate all arg help strings here to locales/en.toml once clap gains
// runtime-string support without requiring a full builder-API rewrite.
#[command(version = env!("CARGO_PKG_VERSION"))]
struct Cli {
    /// Increase verbosity (-v, -vv for more detail)
    #[arg(short, long, action = clap::ArgAction::Count, global = true)]
    verbose: u8,

    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Subcommand)]
enum Command {
    /// Run a unified query (code + annotations) against the project
    #[command(
        long_about = "Run a unified query that joins code elements with annotations via binding keys.\n\nExamples:\n  aql query 'route[method=\"GET\"]' --scope src/routes/\n  aql query 'function[async][export]'\n  aql query 'describe > test' --scope src/"
    )]
    Query {
        /// CSS-like selector (e.g. `route[method="GET"]`, `function[async]`)
        selector: String,
        /// Scope path (directory or file) to limit the query
        #[arg(long)]
        scope: Option<String>,
        /// Return at most N results
        #[arg(long)]
        limit: Option<usize>,
        /// Skip the first N results
        #[arg(long)]
        offset: Option<usize>,
        /// Sort results by field. Prefix with `-` for descending.
        /// Fields: `line`, `name`, `file`, `attr:<name>`
        #[arg(long = "sort-by", allow_hyphen_values = true)]
        sort_by: Option<String>,
    },
    /// Select annotations by selector (annotations only, no code)
    #[command(
        long_about = "Select annotations by CSS-like selector. Does not parse source code.\n\nExamples:\n  aql select 'route[method=\"POST\"]'\n  aql select 'describe > test' --file src/auth.test.ts\n  aql select 'middleware[scope=\"global\"]'"
    )]
    Select {
        /// CSS-like selector (e.g. `middleware[name="cors"]`, `[auth="required"]`)
        selector: String,
        /// Limit to a single file
        #[arg(long)]
        file: Option<String>,
        /// Scope path (directory) to limit the selection
        #[arg(long)]
        scope: Option<String>,
        /// Return at most N results
        #[arg(long)]
        limit: Option<usize>,
        /// Skip the first N results
        #[arg(long)]
        offset: Option<usize>,
        /// Sort results by field. Prefix with `-` for descending.
        /// Fields: `tag`, `file`, `binding`, `attr:<name>`
        #[arg(long = "sort-by", allow_hyphen_values = true)]
        sort_by: Option<String>,
    },
    /// Validate all annotations against the manifest schema
    Validate,
    /// Suggest repairs for broken annotation bindings
    Repair,
    /// Print the parsed manifest schema as JSON
    Schema,
    /// Print the .aqm sidecar location for a source file
    Locate {
        /// Source file path (e.g. src/routes/posts.ts)
        source: String,
        /// Symbol name to jump to (e.g. handleGetPosts)
        #[arg(long)]
        word: Option<String>,
    },
    /// Run a built-in extractor and output JSON
    Extract {
        /// Extractor name (e.g. "express", "test")
        name: String,
        /// Path to source file or directory (default: current directory)
        path: Option<String>,
    },
    /// Show project statistics: file counts, token estimates, compression ratio
    Stats,
    /// Initialize a new AQL project by detecting the stack and generating .config/aql.schema
    Init,
    /// Show annotation changes since the last git commit
    Diff,
    /// Run token savings benchmarks comparing AQL vs baseline approaches
    #[command(
        long_about = "Compare AQL token efficiency against named baseline approaches.\n\nExplicit AQL operation:\n  aql bench --extract test --path src/                         # auto-adds cat baseline\n  aql bench --extract test --path src/ --baseline 'sg=sg -p ...'  # named baselines\n  aql bench --nav-select function_item --path src/main.rs\n  aql bench --query 'route[method=GET]' --path src/\n\nConfig file:\n  aql bench --config .config/aql.bench\n  aql bench  # auto-loads .config/aql.bench if present"
    )]
    Bench {
        /// Run AQL extractor and compare. Names the AQL row in the table.
        #[arg(long)]
        extract: Option<String>,
        /// Run AQL nav-select with this tree-sitter selector. Requires --path (file).
        #[arg(long = "nav-select")]
        nav_select: Option<String>,
        /// Run AQL unified query with this selector. Uses --path as scope.
        #[arg(long)]
        query: Option<String>,
        /// Path or scope for --extract / --nav-select / --query.
        #[arg(long)]
        path: Option<String>,
        /// Named baseline: "name=shell command". Repeatable. Omit to auto-add cat on --path.
        #[arg(long = "baseline")]
        baselines: Vec<String>,
        /// Path to bench config (default: .config/aql.bench)
        #[arg(long)]
        config: Option<String>,
        /// Output JSON instead of table
        #[arg(long)]
        json: bool,
    },
    /// Execute a declarative transaction from a JSON ops file or stdin
    #[command(
        long_about = "Apply an ordered list of mutation ops atomically: all succeed or nothing is written.\n\nOps are a JSON array of TransactionOp objects (see aql nav select/read for NodeRefs).\nWithin a single file, order ops by descending start_byte to avoid offset drift.\n\nExamples:\n  aql transact --file ops.json\n  echo '[{\"type\":\"replace\",\"node\":{...},\"source\":\"x\"}]' | aql transact\n  aql transact --file ops.json --json"
    )]
    Transact {
        /// Path to a JSON file containing a TransactionOp array. Reads stdin if omitted.
        #[arg(long)]
        file: Option<String>,
        /// Output JSON result
        #[arg(long)]
        json: bool,
    },
    /// Start the MCP server (stdio transport)
    Mcp {
        /// Path to the project root (default: auto-detect from cwd)
        #[arg(long)]
        project: Option<String>,
    },
    /// Navigate and mutate source code via tree-sitter AST
    #[command(
        long_about = "Navigate and mutate source code using tree-sitter AST nodes.\n\nExamples:\n  aql nav select --file src/main.rs function_item\n  aql nav read '<node-json>'\n  aql nav insert --position before '<node-json>' '// comment'\n  aql nav replace '<node-json>' 'new_source'\n  aql nav remove '<node-json>'"
    )]
    Nav {
        #[command(subcommand)]
        action: NavAction,
    },
}

#[derive(Subcommand)]
enum NavAction {
    /// Select AST nodes matching a tree-sitter node kind
    Select {
        /// Tree-sitter node kind selector (e.g. "function_item", "function_declaration")
        selector: String,
        /// Relative path to source file
        #[arg(long)]
        file: String,
    },
    /// Read the source text of a node
    Read {
        /// Node reference as JSON (from `aql nav select` output)
        node: String,
    },
    /// Insert source text relative to a target node
    Insert {
        /// Target node reference as JSON
        target: String,
        /// Source text to insert (use `-` to read from stdin)
        source: String,
        /// Position relative to target: before, after, into
        #[arg(long, default_value = "before")]
        position: String,
    },
    /// Replace a node's source text
    Replace {
        /// Node reference as JSON
        node: String,
        /// Replacement source text (use `-` to read from stdin)
        source: String,
    },
    /// Remove a node from its source file
    Remove {
        /// Node reference as JSON
        node: String,
    },
}

fn main() -> ExitCode {
    let cli = Cli::command()
        .name(amql_engine::meta::NAME)
        .about(msg!("cli.about", "full_name" => amql_engine::meta::FULL_NAME))
        .get_matches();
    let cli = Cli::from_arg_matches(&cli).unwrap_or_else(|e| e.exit());

    amql_log::from_verbosity(cli.verbose);

    let _ = color_eyre::install();

    match cli.command {
        Some(cmd) => dispatch_command(cmd),
        None => repl::run_repl(),
    }
}

/// Format and print an error to stderr with optional color.
fn print_error(label: &str, msg: &dyn std::fmt::Display) {
    if std::io::IsTerminal::is_terminal(&std::io::stderr()) {
        eprintln!("\x1b[1;31merror\x1b[0m[{label}]: {msg}");
    } else {
        eprintln!("error[{label}]: {msg}");
    }
}

fn dispatch_command(cmd: Command) -> ExitCode {
    if let Command::Locate { source, word } = cmd {
        return dispatch_locate(&source, word.as_deref());
    }
    if let Command::Extract { name, path } = cmd {
        return dispatch_extract(&name, path.as_deref());
    }
    if matches!(cmd, Command::Init) {
        return dispatch_init();
    }
    if matches!(cmd, Command::Diff) {
        return dispatch_diff();
    }
    if let Command::Bench {
        extract,
        nav_select,
        query,
        path,
        baselines,
        config,
        json,
    } = cmd
    {
        return dispatch_bench(BenchArgs {
            extract: extract.as_deref(),
            nav_select: nav_select.as_deref(),
            query: query.as_deref(),
            path: path.as_deref(),
            raw_baselines: &baselines,
            config_path: config.as_deref(),
            json,
        });
    }
    if let Command::Transact { file, json } = cmd {
        return dispatch_transact(file.as_deref(), json);
    }
    if let Command::Mcp { project } = cmd {
        return dispatch_mcp(project.as_deref());
    }
    if let Command::Nav { action } = cmd {
        return dispatch_nav(action);
    }

    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let project_root = match find_project_root(&cwd) {
        Some(root) => root,
        None => {
            print_error(
                "config",
                &format!(
                    "no {} found in any parent directory\n  hint: create {} to mark the project root",
                    meta::schema_file(), meta::schema_file()
                ),
            );
            return ExitCode::FAILURE;
        }
    };
    info!("project root: {}", project_root.display());

    let manifest = match load_manifest(&project_root) {
        Ok(m) => {
            debug!(
                "manifest: {} tags, {} extractors",
                m.tags.len(),
                m.extractors.len()
            );
            m
        }
        Err(e) => {
            print_error("manifest", &e);
            return ExitCode::FAILURE;
        }
    };

    match cmd {
        Command::Query {
            selector,
            scope,
            limit,
            offset,
            sort_by,
        } => {
            info!("query: {selector}");
            let resolvers = make_resolvers();
            let mut cache = CodeCache::new(&project_root);
            let mut store = AnnotationStore::new(&project_root);
            store.load_all_from_locator();
            load_extractors(&manifest, &project_root, &mut store);

            let scope_str = scope.as_deref().unwrap_or("");
            if !scope_str.is_empty() && !project_root.join(scope_str).exists() {
                print_error(
                    "query",
                    &format_args!("scope path does not exist: {scope_str}"),
                );
                return ExitCode::FAILURE;
            }
            let opts = build_query_opts(limit, offset, sort_by);
            match unified_query(
                &selector,
                &Scope::from(scope_str),
                &mut cache,
                &mut store,
                &resolvers,
                opts.as_ref(),
            ) {
                Ok(results) => {
                    info!("{} results", results.len());
                    if results.is_empty() {
                        if let Some(hint) = tree_sitter_kind_hint(&selector) {
                            eprintln!("hint: {hint}");
                        }
                    }
                    println!("{}", serde_json::to_string_pretty(&results).unwrap());
                    ExitCode::SUCCESS
                }
                Err(e) => {
                    print_error("query", &e);
                    ExitCode::FAILURE
                }
            }
        }
        Command::Select {
            selector,
            file,
            scope,
            limit,
            offset,
            sort_by,
        } => {
            info!("select: {selector}");
            let mut store = AnnotationStore::new(&project_root);
            store.load_all_from_locator();
            load_extractors(&manifest, &project_root, &mut store);

            let scope_str = scope.as_deref().unwrap_or("");
            if !scope_str.is_empty() && !project_root.join(scope_str).exists() {
                print_error(
                    "select",
                    &format_args!("scope path does not exist: {scope_str}"),
                );
                return ExitCode::FAILURE;
            }
            let opts = build_query_opts(limit, offset, sort_by);
            match store.select(&selector, file.as_deref(), scope.as_deref(), opts.as_ref()) {
                Ok(results) => {
                    info!("{} results", results.len());
                    println!("{}", serde_json::to_string_pretty(&results).unwrap());
                    ExitCode::SUCCESS
                }
                Err(e) => {
                    print_error("select", &e);
                    ExitCode::FAILURE
                }
            }
        }
        Command::Validate => {
            let mut store = AnnotationStore::new(&project_root);
            store.load_all_from_locator();

            let results = validate(&store, &manifest);
            info!("{} issues", results.len());
            println!("{}", serde_json::to_string_pretty(&results).unwrap());
            if results
                .iter()
                .any(|r| r.level == amql_engine::ValidationLevel::Error)
            {
                ExitCode::FAILURE
            } else {
                ExitCode::SUCCESS
            }
        }
        Command::Repair => {
            let resolvers = make_resolvers();
            let mut cache = CodeCache::new(&project_root);
            cache.ensure_scope(&Scope::from(""), &resolvers);

            let mut store = AnnotationStore::new(&project_root);
            store.load_all_from_locator();

            let suggestions = suggest_repairs(&store, Some(&cache));
            info!("{} suggestions", suggestions.len());
            println!("{}", serde_json::to_string_pretty(&suggestions).unwrap());
            ExitCode::SUCCESS
        }
        Command::Schema => {
            println!("{}", serde_json::to_string_pretty(&manifest).unwrap());
            ExitCode::SUCCESS
        }
        Command::Stats => {
            let resolvers = make_resolvers();
            let mut store = AnnotationStore::new(&project_root);
            store.load_all_from_locator();
            load_extractors(&manifest, &project_root, &mut store);

            let stats = project_stats(
                &amql_engine::ProjectRoot::from(project_root.as_path()),
                &store,
                &resolvers,
            );
            println!("{}", serde_json::to_string_pretty(&stats).unwrap());
            ExitCode::SUCCESS
        }
        Command::Locate { .. }
        | Command::Extract { .. }
        | Command::Init
        | Command::Diff
        | Command::Bench { .. }
        | Command::Transact { .. }
        | Command::Mcp { .. }
        | Command::Nav { .. } => {
            unreachable!()
        }
    }
}

/// Build a `QueryOptions` from CLI flag values. Returns `None` if all are unset.
fn build_query_opts(
    limit: Option<usize>,
    offset: Option<usize>,
    sort_by: Option<String>,
) -> Option<QueryOptions> {
    if limit.is_none() && offset.is_none() && sort_by.is_none() {
        return None;
    }
    Some(QueryOptions::new(limit, offset, sort_by))
}

/// Run a built-in extractor against a file or directory and output JSON.
fn dispatch_extract(name: &str, path: Option<&str>) -> ExitCode {
    let registry = ExtractorRegistry::with_defaults();
    let builtin = match registry.get(name) {
        Some(e) => e,
        None => {
            print_error(
                "extract",
                &format_args!(
                    "unknown extractor: {name}\navailable: {}",
                    registry.names().join(", ")
                ),
            );
            return ExitCode::FAILURE;
        }
    };

    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let target = path.map(|p| cwd.join(p)).unwrap_or_else(|| cwd.clone());
    info!("extractor: {name}, target: {}", target.display());

    let extensions: rustc_hash::FxHashSet<&str> = builtin
        .extensions()
        .iter()
        .map(|e| e.trim_start_matches('.'))
        .collect();

    let mut source_files: Vec<PathBuf> = Vec::new();
    if target.is_file() {
        source_files.push(target);
    } else if target.is_dir() {
        collect_source_files(&target, &extensions, &mut source_files);
    } else {
        print_error(
            "extract",
            &format_args!("path not found: {}", target.display()),
        );
        return ExitCode::FAILURE;
    }
    debug!("{} source files", source_files.len());

    let project_root = amql_engine::ProjectRoot::from(
        find_project_root(&cwd)
            .unwrap_or_else(|| cwd.clone())
            .as_path(),
    );

    let mut all_annotations = Vec::new();
    for file in &source_files {
        let relative = file
            .strip_prefix(project_root.as_ref())
            .map(|r| amql_engine::RelativePath::from(r.to_string_lossy().as_ref()))
            .unwrap_or_else(|_| amql_engine::RelativePath::from(file.to_string_lossy().as_ref()));

        let source = match std::fs::read_to_string(file) {
            Ok(s) => s,
            Err(e) => {
                print_error(
                    "extract",
                    &format_args!("failed to read {}: {e}", file.display()),
                );
                continue;
            }
        };

        let annotations = builtin.extract(&source, &relative);
        debug!(
            "{}: {} annotations",
            AsRef::<str>::as_ref(&relative),
            annotations.len()
        );
        all_annotations.extend(annotations);
    }

    info!("{} annotations total", all_annotations.len());
    let output = serde_json::json!({ "annotations": all_annotations });
    println!("{}", serde_json::to_string_pretty(&output).unwrap());
    ExitCode::SUCCESS
}

/// Parse inline baselines from command strings.
///
/// Format: `"cmd args..."` — display name auto-derived from the first word.
/// Use `"name=cmd args..."` to override the display name (no spaces in name).
/// Returns true if `s` is a valid baseline identifier (ASCII alpha/underscore start,
/// alphanumeric/hyphen/underscore body). Rejects env-var prefixes like `FOO=1`.
fn is_identifier(s: &str) -> bool {
    !s.is_empty()
        && s.chars()
            .next()
            .map(|c| c.is_ascii_alphabetic() || c == '_')
            .unwrap_or(false)
        && s.chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
}

fn parse_inline_baselines(raw: &[String]) -> Result<Vec<BaselineDef>, String> {
    raw.iter()
        .map(|s| {
            // Explicit name only when left side of `=` is a plain identifier.
            // This avoids misidentifying `FOO=1 rg ...` (env-var prefix) as name="FOO".
            let (name, cmd) = match s.split_once('=') {
                Some((left, right)) if is_identifier(left) => (left.to_string(), right.to_string()),
                _ => {
                    let first = s.split_whitespace().next().unwrap_or(s).to_string();
                    (first, s.clone())
                }
            };
            if name.trim().is_empty() || cmd.trim().is_empty() {
                return Err(format!(
                    "invalid baseline '{s}': name and command must be non-empty"
                ));
            }
            Ok(BaselineDef::Command { name, cmd })
        })
        .collect()
}

struct BenchArgs<'a> {
    extract: Option<&'a str>,
    nav_select: Option<&'a str>,
    query: Option<&'a str>,
    path: Option<&'a str>,
    raw_baselines: &'a [String],
    config_path: Option<&'a str>,
    json: bool,
}

/// Run benchmarks comparing AQL vs baseline token usage.
fn dispatch_bench(args: BenchArgs<'_>) -> ExitCode {
    let BenchArgs {
        extract,
        nav_select,
        query,
        path,
        raw_baselines,
        config_path,
        json,
    } = args;

    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let project_root = find_project_root(&cwd).unwrap_or_else(|| cwd.clone());
    let root = ProjectRoot::from(project_root.as_path());
    let registry = ExtractorRegistry::with_defaults();
    let resolvers = make_resolvers();

    let op_count = [extract.is_some(), nav_select.is_some(), query.is_some()]
        .iter()
        .filter(|&&b| b)
        .count();
    if op_count > 1 {
        print_error(
            "bench",
            &"only one of --extract, --nav-select, --query may be specified",
        );
        return ExitCode::FAILURE;
    }

    let aql_def: Option<AqlDef> = extract
        .map(|extractor| AqlDef::Extract {
            extractor: extractor.to_string(),
            path: path.unwrap_or(".").to_string(),
        })
        .or_else(|| {
            nav_select.map(|selector| AqlDef::NavSelect {
                path: path.unwrap_or(".").to_string(),
                selector: selector.to_string(),
            })
        })
        .or_else(|| {
            query.map(|selector| AqlDef::Query {
                selector: selector.to_string(),
                scope: path.unwrap_or("").to_string(),
            })
        });

    let baselines = match parse_inline_baselines(raw_baselines) {
        Ok(b) => b,
        Err(e) => {
            print_error("bench", &e);
            return ExitCode::FAILURE;
        }
    };

    let req = BenchRequest {
        aql: aql_def,
        path: path.map(|p| p.to_string()),
        baselines,
        config: config_path.map(|p| p.to_string()),
    };

    match execute_bench_request(&root, req, &registry, &resolvers) {
        Ok(response) => {
            if json {
                println!("{}", serde_json::to_string_pretty(&response).unwrap());
            } else {
                print!(
                    "{}",
                    format_bench_table(&response.project, response.source_files, &response.cases)
                );
            }
            let any_aql_error = response.cases.iter().any(|c| c.aql.error.is_some());
            if any_aql_error {
                ExitCode::FAILURE
            } else {
                ExitCode::SUCCESS
            }
        }
        Err(e) => {
            print_error("bench", &e);
            ExitCode::FAILURE
        }
    }
}

/// Print `sidecar_path:line` for a source file. Exits 1 if no sidecar exists.
fn dispatch_locate(source: &str, word: Option<&str>) -> ExitCode {
    let sidecar_rel = sidecar_for_colocated(&amql_engine::RelativePath::from(source));
    let source_path = std::path::Path::new(source);
    let sidecar_path = source_path
        .parent()
        .map(|p| {
            p.join(
                std::path::Path::new(AsRef::<str>::as_ref(&sidecar_rel))
                    .file_name()
                    .unwrap_or_default(),
            )
        })
        .unwrap_or_else(|| PathBuf::from(AsRef::<str>::as_ref(&sidecar_rel)));

    if !sidecar_path.is_file() {
        print_error(
            "locate",
            &format_args!("no sidecar found: {}", sidecar_path.display()),
        );
        return ExitCode::FAILURE;
    }

    let text = match std::fs::read_to_string(&sidecar_path) {
        Ok(t) => t,
        Err(e) => {
            print_error(
                "locate",
                &format_args!("failed to read {}: {e}", sidecar_path.display()),
            );
            return ExitCode::FAILURE;
        }
    };

    let line = word
        .and_then(|w| {
            extract_aql_symbols(&text)
                .iter()
                .find(|s| s.binding.as_ref() == w)
                .map(|s| s.line)
        })
        .unwrap_or(0);

    println!("{}:{}", sidecar_path.display(), line + 1);
    ExitCode::SUCCESS
}

/// Compare current annotations against git HEAD.
fn dispatch_diff() -> ExitCode {
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let project_root = match find_project_root(&cwd) {
        Some(root) => root,
        None => {
            print_error(
                "config",
                &format!("no {} found in any parent directory", meta::schema_file()),
            );
            return ExitCode::FAILURE;
        }
    };

    // Load current annotations
    let mut current_store = AnnotationStore::new(&project_root);
    current_store.load_all_from_locator();

    // Load baseline from git: read each sidecar at HEAD
    let baseline_annotations = match load_baseline_annotations(&project_root) {
        Ok(anns) => anns,
        Err(e) => {
            print_error("diff", &e);
            return ExitCode::FAILURE;
        }
    };

    let current_annotations = current_store.get_all_annotations();
    let current_owned: Vec<_> = current_annotations.into_iter().cloned().collect();

    let diff = diff_annotations(&baseline_annotations, &current_owned);

    println!("{}", serde_json::to_string_pretty(&diff).unwrap());
    if diff.added.is_empty() && diff.removed.is_empty() && diff.changed.is_empty() {
        eprintln!("No annotation changes since last commit.");
    } else {
        eprintln!(
            "{} added, {} removed, {} changed",
            diff.added.len(),
            diff.removed.len(),
            diff.changed.len()
        );
    }
    ExitCode::SUCCESS
}

/// Load annotations from git HEAD for all .aqm files.
fn load_baseline_annotations(
    project_root: &std::path::Path,
) -> Result<Vec<amql_engine::Annotation>, String> {
    // Get list of .aqm files tracked in git at HEAD
    let output = std::process::Command::new("git")
        .args(["ls-tree", "-r", "--name-only", "HEAD"])
        .current_dir(project_root)
        .output()
        .map_err(|e| format!("Failed to run git ls-tree: {e}"))?;

    if !output.status.success() {
        return Err("git ls-tree failed — are you in a git repository with commits?".to_string());
    }

    let file_list = String::from_utf8_lossy(&output.stdout);
    let aql_files: Vec<&str> = file_list
        .lines()
        .filter(|l| l.ends_with(".aqm") && !l.ends_with(".d.aqm"))
        .collect();

    let mut baseline_store = AnnotationStore::new(project_root);

    for aql_file in aql_files {
        let show_output = std::process::Command::new("git")
            .args(["show", &format!("HEAD:{aql_file}")])
            .current_dir(project_root)
            .output()
            .map_err(|e| format!("Failed to read {aql_file} from HEAD: {e}"))?;

        if !show_output.status.success() {
            continue;
        }

        let content = String::from_utf8_lossy(&show_output.stdout);
        // Derive source file from sidecar path (strip .aqm extension)
        let rel_source =
            amql_engine::RelativePath::from(aql_file.strip_suffix(".aqm").unwrap_or(aql_file));
        let _ = baseline_store.load_xml(&rel_source, &content);
    }

    Ok(baseline_store
        .get_all_annotations()
        .into_iter()
        .cloned()
        .collect())
}

/// Start the MCP server over stdio transport.
fn dispatch_mcp(project: Option<&str>) -> ExitCode {
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let project_root = match project {
        Some(p) => PathBuf::from(p),
        None => match find_project_root(&cwd) {
            Some(root) => root,
            None => {
                print_error(
                    "mcp",
                    &format!(
                        "no {} found in any parent directory\n  hint: use --project to specify the project root",
                        meta::schema_file()
                    ),
                );
                return ExitCode::FAILURE;
            }
        },
    };

    // Initialize tracing to stderr so it doesn't interfere with stdio transport
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::from_default_env()
                .add_directive(tracing_subscriber::filter::LevelFilter::WARN.into()),
        )
        .with_writer(std::io::stderr)
        .init();

    let rt = tokio::runtime::Runtime::new().unwrap_or_else(|e| {
        print_error("mcp", &format!("failed to create async runtime: {e}"));
        std::process::exit(1);
    });

    rt.block_on(async {
        let server =
            match tokio::task::block_in_place(|| amql_mcp_server::AqlServer::new(&project_root)) {
                Ok(s) => s,
                Err(e) => {
                    print_error("mcp", &e);
                    return ExitCode::FAILURE;
                }
            };

        match server.serve(rmcp::transport::stdio()).await {
            Ok(service) => {
                if let Err(e) = service.waiting().await {
                    print_error("mcp", &e);
                    return ExitCode::FAILURE;
                }
                ExitCode::SUCCESS
            }
            Err(e) => {
                print_error("mcp", &e);
                ExitCode::FAILURE
            }
        }
    })
}

/// Detect project stack and write `.config/aql.schema`.
fn dispatch_init() -> ExitCode {
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    match init_project(&cwd) {
        Ok(schema) => {
            println!("Created {}:", meta::schema_file());
            println!("{schema}");
            ExitCode::SUCCESS
        }
        Err(e) => {
            print_error("init", &e);
            ExitCode::FAILURE
        }
    }
}

/// Execute a JSON transaction ops array from a file or stdin.
fn dispatch_transact(file: Option<&str>, json_output: bool) -> ExitCode {
    use std::io::Read;

    let raw = match file {
        Some(path) => match std::fs::read_to_string(path) {
            Ok(s) => s,
            Err(e) => {
                print_error("transact", &format!("Failed to read {path}: {e}"));
                return ExitCode::FAILURE;
            }
        },
        None => {
            let mut buf = String::new();
            if let Err(e) = std::io::stdin().read_to_string(&mut buf) {
                print_error("transact", &format!("Failed to read stdin: {e}"));
                return ExitCode::FAILURE;
            }
            buf
        }
    };

    let ops: Vec<TransactionOp> = match serde_json::from_str(&raw) {
        Ok(o) => o,
        Err(e) => {
            print_error("transact", &format!("Invalid ops JSON: {e}"));
            return ExitCode::FAILURE;
        }
    };

    if ops.is_empty() {
        print_error("transact", &"ops array must be non-empty");
        return ExitCode::FAILURE;
    }

    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let project_root = match find_project_root(&cwd) {
        Some(root) => root,
        None => {
            print_error(
                "transact",
                &format!("no {} found in any parent directory", meta::schema_file()),
            );
            return ExitCode::FAILURE;
        }
    };

    let project_root = ProjectRoot::from(project_root.as_path());
    match execute_transaction(&project_root, ops) {
        Ok(result) => {
            if json_output {
                println!("{}", serde_json::to_string_pretty(&result).unwrap());
            } else {
                println!(
                    "Transaction committed: {} file(s) modified, {} op(s) applied.",
                    result.files_modified.len(),
                    result.ops_applied
                );
                for f in &result.files_modified {
                    println!("  {f}");
                }
            }
            ExitCode::SUCCESS
        }
        Err(e) => {
            print_error("transact", &e);
            ExitCode::FAILURE
        }
    }
}

/// Read a source text argument: if `"-"`, read from stdin; otherwise use the literal value.
fn read_source_arg(arg: &str) -> Result<String, String> {
    if arg == "-" {
        use std::io::Read;
        let mut buf = String::new();
        std::io::stdin()
            .read_to_string(&mut buf)
            .map_err(|e| format!("Failed to read stdin: {e}"))?;
        Ok(buf)
    } else {
        Ok(arg.to_string())
    }
}

/// Parse a JSON string into a NodeRef.
fn parse_node_ref(json: &str) -> Result<NodeRef, String> {
    serde_json::from_str(json).map_err(|e| format!("Invalid node JSON: {e}"))
}

/// Dispatch `aql nav` subcommands.
fn dispatch_nav(action: NavAction) -> ExitCode {
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let root_path = find_project_root(&cwd).unwrap_or_else(|| cwd.clone());
    let project_root = ProjectRoot::from(root_path.as_path());

    match action {
        NavAction::Select { selector, file } => {
            let rel = RelativePath::from(file.as_str());
            match nav_select(&project_root, &rel, None, &selector) {
                Ok(result) => {
                    println!("{}", serde_json::to_string_pretty(&result).unwrap());
                    ExitCode::SUCCESS
                }
                Err(e) => {
                    print_error("nav/select", &e);
                    ExitCode::FAILURE
                }
            }
        }
        NavAction::Read { node } => match parse_node_ref(&node) {
            Ok(node_ref) => match read_source(&project_root, &node_ref) {
                Ok(text) => {
                    print!("{text}");
                    ExitCode::SUCCESS
                }
                Err(e) => {
                    print_error("nav/read", &e);
                    ExitCode::FAILURE
                }
            },
            Err(e) => {
                print_error("nav/read", &e);
                ExitCode::FAILURE
            }
        },
        NavAction::Insert {
            target,
            source,
            position,
        } => {
            let pos = match position.as_str() {
                "before" => InsertPosition::Before,
                "after" => InsertPosition::After,
                "into" => InsertPosition::Into,
                other => {
                    print_error(
                        "nav/insert",
                        &format_args!("invalid position: {other} (expected: before, after, into)"),
                    );
                    return ExitCode::FAILURE;
                }
            };
            let target_ref = match parse_node_ref(&target) {
                Ok(r) => r,
                Err(e) => {
                    print_error("nav/insert", &e);
                    return ExitCode::FAILURE;
                }
            };
            let text = match read_source_arg(&source) {
                Ok(t) => t,
                Err(e) => {
                    print_error("nav/insert", &e);
                    return ExitCode::FAILURE;
                }
            };
            match nav_insert(&project_root, &target_ref, pos, &text) {
                Ok(result) => {
                    println!("{}", serde_json::to_string_pretty(&result).unwrap());
                    ExitCode::SUCCESS
                }
                Err(e) => {
                    print_error("nav/insert", &e);
                    ExitCode::FAILURE
                }
            }
        }
        NavAction::Replace { node, source } => {
            let node_ref = match parse_node_ref(&node) {
                Ok(r) => r,
                Err(e) => {
                    print_error("nav/replace", &e);
                    return ExitCode::FAILURE;
                }
            };
            let text = match read_source_arg(&source) {
                Ok(t) => t,
                Err(e) => {
                    print_error("nav/replace", &e);
                    return ExitCode::FAILURE;
                }
            };
            match nav_replace(&project_root, &node_ref, &text) {
                Ok(result) => {
                    println!("{}", serde_json::to_string_pretty(&result).unwrap());
                    ExitCode::SUCCESS
                }
                Err(e) => {
                    print_error("nav/replace", &e);
                    ExitCode::FAILURE
                }
            }
        }
        NavAction::Remove { node } => match parse_node_ref(&node) {
            Ok(node_ref) => match nav_remove(&project_root, &node_ref) {
                Ok((result, detached)) => {
                    let output = serde_json::json!({
                        "source": result.source,
                        "affected_nodes": result.affected_nodes,
                        "detached": detached,
                    });
                    println!("{}", serde_json::to_string_pretty(&output).unwrap());
                    ExitCode::SUCCESS
                }
                Err(e) => {
                    print_error("nav/remove", &e);
                    ExitCode::FAILURE
                }
            },
            Err(e) => {
                print_error("nav/remove", &e);
                ExitCode::FAILURE
            }
        },
    }
}

fn make_resolvers() -> ResolverRegistry {
    ResolverRegistry::with_defaults()
}

const SKIP_DIRS: &[&str] = &[
    "node_modules",
    ".git",
    "dist",
    "build",
    "target",
    "coverage",
];

/// Recursively collect source files matching the given extensions into `out`.
fn collect_source_files(
    dir: &std::path::Path,
    extensions: &rustc_hash::FxHashSet<&str>,
    out: &mut Vec<PathBuf>,
) {
    let entries = match std::fs::read_dir(dir) {
        Ok(e) => e,
        Err(_) => return,
    };
    let mut sorted: Vec<_> = entries.flatten().collect();
    sorted.sort_by_key(|e| e.file_name());

    for entry in sorted {
        let path = entry.path();
        if path.is_dir() {
            let name = entry.file_name();
            let name_str = name.to_string_lossy();
            if !SKIP_DIRS.contains(&name_str.as_ref()) {
                collect_source_files(&path, extensions, out);
            }
        } else if path.is_file() {
            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
            if extensions.contains(ext) {
                let fname = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
                if !fname.ends_with(".d.ts")
                    && !fname.ends_with(".d.mts")
                    && !fname.ends_with(".d.cts")
                {
                    out.push(path);
                }
            }
        }
    }
}

/// Tree-sitter node kinds that users might try as selectors.
/// Maps tree-sitter kind → suggested AQL selector.
const TS_KIND_HINTS: &[(&str, &str)] = &[
    ("arrow_function", "function[arrow]"),
    ("function_declaration", "function"),
    ("function_expression", "function"),
    ("generator_function_declaration", "function[generator]"),
    ("class_declaration", "class"),
    ("abstract_class_declaration", "class[abstract]"),
    ("method_definition", "method"),
    ("interface_declaration", "interface"),
    ("type_alias_declaration", "type"),
    ("enum_declaration", "enum"),
    ("function_item", "function"),
    ("struct_item", "struct"),
    ("enum_item", "enum"),
    ("trait_item", "trait"),
    ("impl_item", "impl"),
    ("mod_item", "module"),
    ("lexical_declaration", "const"),
    ("variable_declaration", "const"),
];

/// If the selector tag looks like a tree-sitter node kind, suggest the AQL equivalent.
fn tree_sitter_kind_hint(selector: &str) -> Option<String> {
    let tag = selector.split('[').next().unwrap_or(selector).trim();
    TS_KIND_HINTS
        .iter()
        .find(|(kind, _)| *kind == tag)
        .map(|(kind, suggestion)| {
            format!(
                "'{kind}' is a tree-sitter node kind, not an AQL tag. Try: aql query '{suggestion}'"
            )
        })
}

/// Merge extractor-produced annotations into the store.
fn load_extractors(
    manifest: &amql_engine::Manifest,
    project_root: &std::path::Path,
    store: &mut AnnotationStore,
) {
    let project_root = amql_engine::ProjectRoot::from(project_root);
    let registry = ExtractorRegistry::with_defaults();
    let results = run_all_extractors(manifest, &project_root, &registry);
    for result in results {
        if !result.annotations.is_empty() {
            store.load_extractor_output(result.annotations);
        }
    }
}