fraiseql-cli 2.15.0

CLI tools for FraiseQL v2 - Schema compilation and development utilities
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
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
//! CLI argument definitions: `Cli` struct, `Commands` enum, and all sub-command enums.

use clap::{Parser, Subcommand};

/// Exit codes documented in help text
pub(crate) const EXIT_CODES_HELP: &str = "\
EXIT CODES:
    0  Success - Command completed successfully
    1  Error - Command failed with an error
    2  Validation failed - Schema or input validation failed";

/// FraiseQL CLI - Compile GraphQL schemas to optimized SQL execution
#[derive(Parser)]
#[command(name = "fraiseql")]
#[command(author, version, about, long_about = None)]
#[command(propagate_version = true)]
#[command(after_help = EXIT_CODES_HELP)]
pub(crate) struct Cli {
    /// Enable verbose logging
    #[arg(short, long, global = true)]
    pub(crate) verbose: bool,

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

    /// Output as JSON (machine-readable)
    #[arg(long, global = true)]
    pub(crate) json: bool,

    /// Suppress output (exit code only)
    #[arg(short, long, global = true)]
    pub(crate) quiet: bool,

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

#[derive(Subcommand)]
pub(crate) enum Commands {
    /// Compile schema to optimized schema.compiled.json
    ///
    /// Supports three workflows:
    /// 1. TOML-only: fraiseql compile fraiseql.toml
    /// 2. Language + TOML: fraiseql compile fraiseql.toml --types types.json
    /// 3. Legacy JSON: fraiseql compile schema.json
    #[command(after_help = "\
EXAMPLES:
    fraiseql compile fraiseql.toml
    fraiseql compile fraiseql.toml --types types.json
    fraiseql compile schema.json -o schema.compiled.json
    fraiseql compile fraiseql.toml --check")]
    Compile {
        /// Input file path: fraiseql.toml (TOML) or schema.json (legacy)
        #[arg(value_name = "INPUT")]
        input: String,

        /// Optional types.json from language implementation (used with fraiseql.toml)
        #[arg(long, value_name = "TYPES")]
        types: Option<String>,

        /// Directory for auto-discovery of schema files (recursive *.json)
        #[arg(long, value_name = "DIR")]
        schema_dir: Option<String>,

        /// Type files (repeatable): fraiseql compile fraiseql.toml --type-file a.json --type-file
        /// b.json
        #[arg(long = "type-file", value_name = "FILE")]
        type_files: Vec<String>,

        /// Query files (repeatable)
        #[arg(long = "query-file", value_name = "FILE")]
        query_files: Vec<String>,

        /// Mutation files (repeatable)
        #[arg(long = "mutation-file", value_name = "FILE")]
        mutation_files: Vec<String>,

        /// Output schema.compiled.json file path
        #[arg(
            short,
            long,
            value_name = "OUTPUT",
            default_value = "schema.compiled.json"
        )]
        output: String,

        /// Validate only, don't write output
        #[arg(long)]
        check: bool,

        /// Skip embedding content hash in compiled schema (for test fixtures)
        #[arg(long)]
        skip_hash: bool,

        /// Optional database URL for indexed column validation
        /// When provided, validates that indexed columns exist in database views
        #[arg(long, value_name = "DATABASE_URL")]
        database: Option<String>,

        /// Emit DDL files for all schema types to the given directory
        ///
        /// Writes `CREATE TABLE` DDL for each compiled type to `<DIR>/<type>.sql`.
        /// Output is compatible with confiture's `db/schema/` directory format,
        /// enabling `fraiseql migrate generate` to auto-detect schema drift.
        #[arg(long, value_name = "DIR")]
        emit_ddl: Option<String>,

        /// Check compiled schema against the database for migration drift
        ///
        /// Emits DDL to a temporary directory, then delegates to
        /// `confiture migrate validate` for drift detection.
        /// Exits non-zero when the compiled schema diverges from the database.
        #[arg(long)]
        check_migrations: bool,

        /// Compile despite error-severity schema↔database drift (advisory mode)
        ///
        /// With `--database`, drift the linter classifies as an error (a
        /// `sql_source` that does not exist, a required field's JSONB key
        /// absent from every sampled row, a mutation with no backing function)
        /// fails the compile. This flag downgrades those findings to reported
        /// advisories and writes the artifact anyway.
        #[arg(long, requires = "database")]
        allow_drift: bool,
    },

    /// Extract schema from annotated source files
    ///
    /// Parses FraiseQL annotations in any supported language and generates schema.json.
    /// No language runtime required — pure text processing.
    #[command(after_help = "\
EXAMPLES:
    fraiseql extract schema/schema.py
    fraiseql extract schema/ --recursive
    fraiseql extract schema.rs --language rust -o schema.json")]
    Extract {
        /// Source file(s) or directory to extract from
        #[arg(value_name = "INPUT")]
        input: Vec<String>,

        /// Override language detection (python, typescript, rust, java, kotlin, go, csharp, swift,
        /// scala)
        #[arg(short, long)]
        language: Option<String>,

        /// Recursively scan directories
        #[arg(short, long)]
        recursive: bool,

        /// Output file path
        #[arg(short, long, default_value = "schema.json")]
        output: String,
    },

    /// Explain query execution plan and complexity
    ///
    /// Shows GraphQL query execution plan, SQL, and complexity analysis.
    #[command(after_help = "\
EXAMPLES:
    fraiseql explain '{ users { id name } }'
    fraiseql explain '{ user(id: 1) { posts { title } } }' --json")]
    Explain {
        /// GraphQL query string
        #[arg(value_name = "QUERY")]
        query: String,
    },

    /// Calculate query complexity score
    ///
    /// Quick analysis of query complexity (depth, field count, score).
    #[command(after_help = "\
EXAMPLES:
    fraiseql cost '{ users { id name } }'
    fraiseql cost '{ deeply { nested { query { here } } } }' --json")]
    Cost {
        /// GraphQL query string
        #[arg(value_name = "QUERY")]
        query: String,
    },

    /// Analyze schema for optimization opportunities
    ///
    /// Provides recommendations across 6 categories:
    /// performance, security, federation, complexity, caching, indexing
    #[command(after_help = "\
EXAMPLES:
    fraiseql analyze schema.compiled.json
    fraiseql analyze schema.compiled.json --json")]
    Analyze {
        /// Path to schema.compiled.json
        #[arg(value_name = "SCHEMA")]
        schema: String,
    },

    /// Analyze schema type dependencies
    ///
    /// Exports dependency graph, detects cycles, and finds unused types.
    /// Supports multiple output formats for visualization and CI integration.
    #[command(after_help = "\
EXAMPLES:
    fraiseql dependency-graph schema.compiled.json
    fraiseql dependency-graph schema.compiled.json -f dot > graph.dot
    fraiseql dependency-graph schema.compiled.json -f mermaid
    fraiseql dependency-graph schema.compiled.json --json")]
    DependencyGraph {
        /// Path to schema.compiled.json
        #[arg(value_name = "SCHEMA")]
        schema: String,

        /// Output format (json, dot, mermaid, d2, console)
        #[arg(short, long, value_name = "FORMAT", default_value = "json")]
        format: String,
    },

    /// Export federation dependency graph
    ///
    /// Visualize federation structure in multiple formats.
    #[command(after_help = "\
EXAMPLES:
    fraiseql federation graph schema.compiled.json
    fraiseql federation graph schema.compiled.json -f dot
    fraiseql federation graph schema.compiled.json -f mermaid")]
    Federation {
        /// Schema path (positional argument passed to subcommand)
        #[command(subcommand)]
        command: FederationCommands,
    },

    /// Lint schema for FraiseQL design quality
    ///
    /// Analyzes schema using FraiseQL-calibrated design rules.
    /// Detects JSONB batching issues, compilation problems, auth boundaries, etc.
    #[command(after_help = "\
EXAMPLES:
    fraiseql lint schema.json
    fraiseql lint schema.compiled.json --federation
    fraiseql lint schema.json --fail-on-critical
    fraiseql lint schema.json --json")]
    Lint {
        /// Path to schema.json or schema.compiled.json
        #[arg(value_name = "SCHEMA")]
        schema: String,

        /// Only show federation audit
        #[arg(long)]
        federation: bool,

        /// Only show cost audit
        #[arg(long)]
        cost: bool,

        /// Only show cache audit
        #[arg(long)]
        cache: bool,

        /// Only show auth audit
        #[arg(long)]
        auth: bool,

        /// Only show compilation audit
        #[arg(long)]
        compilation: bool,

        /// Exit with error if any critical issues found
        #[arg(long)]
        fail_on_critical: bool,

        /// Exit with error if any warning or critical issues found
        #[arg(long)]
        fail_on_warning: bool,
    },

    /// Generate DDL for Arrow views (va_*, tv_*, ta_*)
    #[command(after_help = "\
EXAMPLES:
    fraiseql generate-views -s schema.json -e User --view va_users
    fraiseql generate-views -s schema.json -e Order --view tv_orders --refresh-strategy scheduled")]
    GenerateViews {
        /// Path to schema.json
        #[arg(short, long, value_name = "SCHEMA")]
        schema: String,

        /// Entity name from schema
        #[arg(short, long, value_name = "NAME")]
        entity: String,

        /// View name (must start with va_, tv_, or ta_)
        #[arg(long, value_name = "NAME")]
        view: String,

        /// Refresh strategy (trigger-based or scheduled)
        #[arg(long, value_name = "STRATEGY", default_value = "trigger-based")]
        refresh_strategy: String,

        /// Output file path (default: {view}.sql)
        #[arg(short, long, value_name = "PATH")]
        output: Option<String>,

        /// Include helper/composition views
        #[arg(long, default_value = "true")]
        include_composition_views: bool,

        /// Include monitoring functions
        #[arg(long, default_value = "true")]
        include_monitoring: bool,

        /// Validate the generated DDL by executing it against PostgreSQL
        /// (DATABASE_URL) in a rolled-back transaction; don't write a file
        #[arg(long)]
        validate: bool,

        /// Show generation steps (use global --verbose flag)
        #[arg(long, action = clap::ArgAction::SetTrue)]
        gen_verbose: bool,
    },

    /// Generate external-write capture-trigger DDL for @subscribable types (#366)
    ///
    /// Emits a self-contained, idempotent PostgreSQL script (the capture function
    /// plus per-table statement-level triggers) that brings raw external writes
    /// (psql / migrations / third-party tools) to a `@subscribable` type's table(s)
    /// onto the Change Spine, without double-emitting for FraiseQL-mediated writes.
    #[command(after_help = "\
EXAMPLES:
    fraiseql generate-capture-triggers -s schema.compiled.json | psql \"$DATABASE_URL\"
    fraiseql generate-capture-triggers -s schema.compiled.json -o capture.sql")]
    GenerateCaptureTriggers {
        /// Path to the compiled schema (schema.compiled.json)
        #[arg(short, long, value_name = "SCHEMA")]
        schema: String,

        /// Output file path (default: stdout, for piping into psql)
        #[arg(short, long, value_name = "PATH")]
        output: Option<String>,

        /// Omit the capture function definition (emit only the per-table triggers)
        #[arg(long)]
        no_function: bool,
    },

    /// Validate schema.json or fact tables
    ///
    /// Performs comprehensive schema validation including:
    /// - JSON structure validation
    /// - Type reference validation
    /// - Circular dependency detection (with --check-cycles)
    /// - Unused type detection (with --check-unused)
    #[command(after_help = "\
EXAMPLES:
    fraiseql validate schema.json
    fraiseql validate schema.json --check-unused
    fraiseql validate schema.json --strict
    fraiseql validate facts -s schema.json --database postgres://localhost/db")]
    Validate {
        #[command(subcommand)]
        command: Option<ValidateCommands>,

        /// Schema.json file path to validate (if no subcommand)
        #[arg(value_name = "INPUT")]
        input: Option<String>,

        /// Check for circular dependencies between types
        #[arg(long, default_value = "true")]
        check_cycles: bool,

        /// Check for unused types (no incoming references)
        #[arg(long)]
        check_unused: bool,

        /// Strict mode: treat warnings as errors (unused types become errors)
        #[arg(long)]
        strict: bool,

        /// Only analyze specific type(s) - comma-separated list
        #[arg(long, value_name = "TYPES", value_delimiter = ',')]
        types: Vec<String>,

        /// Validate the mutation contract against a live PostgreSQL database.
        ///
        /// For each DB-backed mutation, checks that its `sql_source` function
        /// exists with the argument layout the server sends and returns the
        /// columns the server decodes into `MutationResponse`. Requires a
        /// compiled schema (schema.compiled.json) as INPUT. (#397)
        #[arg(long, value_name = "DATABASE_URL")]
        against_db: Option<String>,
    },

    /// Introspect database for fact tables and output suggestions
    #[command(after_help = "\
EXAMPLES:
    fraiseql introspect facts --database postgres://localhost/db
    fraiseql introspect facts --database postgres://localhost/db -f json")]
    Introspect {
        #[command(subcommand)]
        command: IntrospectCommands,
    },

    /// Generate authoring-language source from schema.json
    ///
    /// The inverse of `fraiseql extract`: reads a schema.json and produces annotated
    /// source code in any of the 9 supported authoring languages.
    #[command(after_help = "\
EXAMPLES:
    fraiseql generate schema.json --language python
    fraiseql generate schema.json --language rust -o schema.rs
    fraiseql generate schema.json --language typescript")]
    Generate {
        /// Path to schema.json
        #[arg(value_name = "INPUT")]
        input: String,

        /// Target language (python, typescript, rust, java, kotlin, go, csharp, swift, scala)
        #[arg(short, long)]
        language: String,

        /// Output file path (default: schema.<ext> based on language)
        #[arg(short, long)]
        output: Option<String>,
    },

    /// Generate consumer-side typed clients from a compiled schema
    ///
    /// Distinct from `generate`: `generate` emits server-side authoring code (write
    /// FraiseQL types in another language, fed back into the compiler), whereas
    /// `generate-client` emits a typed client for callers of a FraiseQL API
    /// (interfaces + query/mutation functions) from a compiled schema.compiled.json.
    #[command(after_help = "\
EXAMPLES:
    fraiseql generate-client typescript --out ./src/generated
    fraiseql generate-client typescript --schema ./schema.compiled.json --out ./gen --force
    fraiseql generate-client python --out ./app/fraiseql_client
    fraiseql generate-client go --out ./internal/fraiseqlclient
    fraiseql generate-client rust --out ./src/generated")]
    GenerateClient {
        #[command(subcommand)]
        language: GenerateClientCommands,
    },

    /// Initialize a new FraiseQL project
    ///
    /// Creates project directory with fraiseql.toml, schema.json,
    /// database DDL structure, and authoring skeleton.
    #[command(after_help = "\
EXAMPLES:
    fraiseql init my-app
    fraiseql init my-app --language typescript --database postgres
    fraiseql init my-app --size xs --no-git")]
    Init {
        /// Project name (used as directory name)
        #[arg(value_name = "PROJECT_NAME")]
        project_name: String,

        /// Authoring language (python, typescript, rust, java, kotlin, go, csharp, swift, scala)
        #[arg(short, long, default_value = "python")]
        language: String,

        /// Target database (postgres — FraiseQL is PostgreSQL-only since v2.15.0)
        #[arg(long, default_value = "postgres")]
        database: String,

        /// Project size: xs (single file), s (flat dirs), m (per-entity dirs)
        #[arg(long, default_value = "s")]
        size: String,

        /// Skip git init
        #[arg(long)]
        no_git: bool,
    },

    /// Run database migrations
    ///
    /// Wraps confiture for a unified migration experience.
    /// Reads database URL from --database, fraiseql.toml, or DATABASE_URL env var.
    #[command(after_help = "\
EXAMPLES:
    fraiseql migrate up --database postgres://localhost/mydb
    fraiseql migrate down --steps 1
    fraiseql migrate status
    fraiseql migrate create add_posts_table")]
    Migrate {
        #[command(subcommand)]
        command: MigrateCommands,
    },

    /// Generate Software Bill of Materials
    ///
    /// Parses Cargo.lock and fraiseql.toml to produce a compliance-ready SBOM.
    #[command(after_help = "\
EXAMPLES:
    fraiseql sbom
    fraiseql sbom --format spdx
    fraiseql sbom --format cyclonedx --output sbom.json")]
    Sbom {
        /// Output format (cyclonedx, spdx)
        #[arg(short, long, default_value = "cyclonedx")]
        format: String,

        /// Output file path (default: stdout)
        #[arg(short, long, value_name = "FILE")]
        output: Option<String>,
    },

    /// Compile schema and immediately start the GraphQL server
    ///
    /// Compiles the schema in-memory (no disk artifact) and starts the HTTP server.
    /// With --watch, the server hot-reloads whenever the schema file changes.
    ///
    /// Server and database settings can be declared in fraiseql.toml under [server]
    /// and [database] sections.  CLI flags take precedence over TOML settings, which
    /// take precedence over defaults.  The database URL is resolved in this order:
    /// --database flag > DATABASE_URL env var > [database].url in fraiseql.toml.
    #[cfg(feature = "run-server")]
    #[command(after_help = "\
EXAMPLES:
    fraiseql run
    fraiseql run fraiseql.toml --database postgres://localhost/mydb
    fraiseql run --port 3000 --watch
    fraiseql run schema.json --introspection

TOML CONFIG:
    [server]
    host = \"127.0.0.1\"
    port = 9000

    [server.cors]
    origins = [\"https://app.example.com\"]

    [database]
    url      = \"${DATABASE_URL}\"
    pool_min = 2
    pool_max = 20")]
    Run {
        /// Input file path (fraiseql.toml or schema.json); auto-detected if omitted
        #[arg(value_name = "INPUT")]
        input: Option<String>,

        /// Database URL (overrides [database].url in fraiseql.toml and DATABASE_URL env var)
        // Long-only: the global `--debug` (`Cli.debug`) already owns `-d`. A local
        // `-d`/`--database` short here collides with it — clap's debug_asserts panic in
        // debug builds and the short is ambiguous in release builds (#650).
        #[arg(long, value_name = "DATABASE_URL")]
        database: Option<String>,

        /// Port to listen on (overrides [server].port in fraiseql.toml)
        #[arg(short, long, value_name = "PORT")]
        port: Option<u16>,

        /// Bind address (overrides [server].host in fraiseql.toml)
        #[arg(long, value_name = "HOST")]
        bind: Option<String>,

        /// Watch input file for changes and hot-reload the server
        #[arg(short, long)]
        watch: bool,

        /// Enable the GraphQL introspection endpoint (no auth required)
        #[arg(long)]
        introspection: bool,
    },

    /// Watch a schema source and recompile + live-reload a running server on change
    ///
    /// Recompiles `schema.compiled.json` on every save and, with `--reload-url`,
    /// POSTs it to a running server's `/api/v1/admin/reload-schema` endpoint for a
    /// zero-downtime `ArcSwap` reload (no restart). Unlike `run --watch`, this drives
    /// a server you started separately.
    Watch {
        /// Schema source to watch (fraiseql.toml or schema.json)
        #[arg(value_name = "INPUT")]
        input: String,

        /// Compiled-schema output path (the server reads this on reload)
        #[arg(short, long, default_value = "schema.compiled.json")]
        output: String,

        /// Base URL of a running server to live-reload (e.g. http://localhost:8080).
        /// Omit to recompile to disk only.
        #[arg(long, value_name = "URL")]
        reload_url: Option<String>,

        /// Bearer token for the server's admin reload endpoint
        #[arg(long, value_name = "TOKEN")]
        admin_token: Option<String>,

        /// Database URL for compile-time validation (overrides DATABASE_URL)
        #[arg(long, value_name = "DATABASE_URL")]
        database: Option<String>,
    },

    /// Validate a trusted documents manifest
    ///
    /// Checks that the manifest JSON is well-formed and that each key
    /// is a valid SHA-256 hex string matching its query body.
    #[command(after_help = "\
EXAMPLES:
    fraiseql validate-documents manifest.json
    fraiseql validate-documents manifest.json --max-cost 1000 --schema schema.compiled.json")]
    ValidateDocuments {
        /// Path to the trusted documents manifest JSON file
        #[arg(value_name = "MANIFEST")]
        manifest: String,

        /// Fail validation when any document's estimated operation cost exceeds
        /// this ceiling (#379). Costs are worst-case: a variable-valued
        /// pagination argument is scored at its fail-closed ceiling.
        #[arg(long, value_name = "COST")]
        max_cost: Option<u64>,

        /// Compiled schema (`schema.compiled.json`) supplying the
        /// `[fraiseql.cost_weights]` used to score documents — the same numbers
        /// the runtime enforces. Without it, cost equals the complexity score.
        #[arg(long, value_name = "SCHEMA")]
        schema: Option<String>,
    },

    /// Install FraiseQL mutation helper functions
    ///
    /// Installs SQL helper functions (fraiseql.mutation_ok, fraiseql.mutation_err, etc.)
    /// to reduce boilerplate when writing mutation functions under the v2.3.0 protocol.
    /// The helpers are installed in the `fraiseql` schema, which is owned by FraiseQL's
    /// database role.
    #[command(after_help = "\
EXAMPLES:
    fraiseql setup --database postgres://localhost/mydb
    fraiseql setup --dry-run
    fraiseql setup  # Uses DATABASE_URL or [database].url from fraiseql.toml")]
    Setup {
        /// Database connection URL (or use DATABASE_URL env var, or [database].url in
        /// fraiseql.toml)
        #[arg(long, value_name = "DATABASE_URL")]
        database: Option<String>,

        /// Print SQL without applying changes
        #[arg(long)]
        dry_run: bool,
    },

    /// Inspect schema metadata from a running FraiseQL server
    ///
    /// Fetches field-level security metadata (encryption, scope requirements, deny actions)
    /// from the server's `/api/v1/schema/metadata` endpoint and displays it as a table.
    #[command(after_help = "\
EXAMPLES:
    fraiseql schema metadata
    fraiseql schema metadata --server http://localhost:8080
    fraiseql schema metadata --server https://api.example.com --token mytoken")]
    Schema {
        #[command(subcommand)]
        command: SchemaCommands,
    },

    /// Execute one GraphQL operation against a database and print the JSON result
    ///
    /// Boots the compiled schema in-process (no long-lived server, no HTTP layer)
    /// against PostgreSQL, runs a single query or mutation, prints the GraphQL JSON
    /// response to stdout, and exits. Exits non-zero on a resolution error — a
    /// scriptable "does this actually resolve?" check for CI and the inner loop.
    ///
    /// Mutations COMMIT unless `--dry-run` is given, which runs the mutation inside
    /// a transaction that is rolled back (validate-bind-without-commit).
    #[command(after_help = "\
EXAMPLES:
    fraiseql query '{ orders(limit: 1) { id } }'
    fraiseql query --schema schema.compiled.json --database postgres://localhost/db '{ users { id } }'
    fraiseql query --variables '{\"id\": 42}' 'query($id: Int!) { user(id: $id) { id } }'
    fraiseql query --dry-run 'mutation { createUser(name: \"x\") { id } }'")]
    Query {
        /// GraphQL operation to execute (a single query or mutation document).
        #[arg(value_name = "QUERY")]
        query: String,

        /// Path to schema.compiled.json.
        #[arg(short = 's', long, default_value = "schema.compiled.json")]
        schema: std::path::PathBuf,

        /// Database URL (PostgreSQL only). Falls back to the DATABASE_URL env var.
        #[arg(long, value_name = "DATABASE_URL")]
        database: Option<String>,

        /// GraphQL variables as a JSON object string (e.g. '{"id": 42}').
        #[arg(long, value_name = "JSON")]
        variables: Option<String>,

        /// Run mutations inside a rolled-back transaction: the function binds and
        /// executes (constraints, triggers, and response shape are validated) but
        /// nothing is committed. No effect on queries. PostgreSQL only.
        #[arg(long)]
        dry_run: bool,
    },

    /// Run diagnostic checks for common FraiseQL setup problems
    ///
    /// Checks schema file, TOML config, DATABASE_URL, JWT secret, Redis, TLS,
    /// and cache/auth coherence. Prints a color-coded report and exits 0 if
    /// all checks pass or 1 if any check fails (warnings do not fail).
    #[command(after_help = "\
EXAMPLES:
    fraiseql doctor
    fraiseql doctor --schema schema.compiled.json --config fraiseql.toml
    fraiseql doctor --db-url postgres://user:pass@host:5432/db
    fraiseql doctor --runtime --against-db postgres://user:pass@host:5432/db
    fraiseql doctor --json")]
    Doctor {
        /// Path to fraiseql.toml configuration file.
        #[arg(long, default_value = "fraiseql.toml")]
        config: std::path::PathBuf,

        /// Path to schema.compiled.json.
        #[arg(long, default_value = "schema.compiled.json")]
        schema: std::path::PathBuf,

        /// Override DATABASE_URL for the connectivity check.
        #[arg(long)]
        db_url: Option<String>,

        /// Run the live-database passes against this PostgreSQL database: the
        /// change-log contract drift check (compares core.tb_entity_change_log
        /// against the shipped contract — #380), the PL/pgSQL body-resolution
        /// pass (reports internal calls that no longer resolve — #409), the
        /// mutation→function contract drift check (every declared mutation has a
        /// matching backing function with a mutation_response-shaped return —
        /// #384), and the view-drift check (the same L1/L2/L3 view-composition
        /// linter `compile --database` runs, reported as structured checks —
        /// #384).
        ///
        /// The body-resolution pass requires the `plpgsql_check` extension and
        /// skips with a hint when it is unavailable.
        #[arg(long, value_name = "DATABASE_URL")]
        against_db: Option<String>,

        /// Runtime smoke mode (#501): boot the compiled schema in-process and
        /// probe each root query field with a minimal selection, dry-running each
        /// no-argument mutation (rolled back). Confirms operations actually
        /// *resolve* end-to-end, complementing the static `--against-db` drift
        /// checks. Requires a PostgreSQL URL via `--against-db` (or `--db-url`).
        /// Queries / mutations that require arguments are skipped with a warning.
        #[arg(long)]
        runtime: bool,

        /// Schemas to scan in the body-resolution pass (comma-separated).
        #[arg(
            long,
            value_name = "SCHEMAS",
            value_delimiter = ',',
            default_value = "public"
        )]
        schemas: Vec<String>,

        /// Output machine-readable JSON (for CI integration).
        #[arg(long)]
        json: bool,
    },

    /// Change-log performance observability (#392)
    ///
    /// Reads the framework-owned change-log (`core.v_entity_change_log`) and turns
    /// it into operator-facing forensics: latency regressions between two time
    /// windows, and ad-hoc reads of the slowest mutations / duration completeness
    /// / per-operation percentiles.
    Perf {
        #[command(subcommand)]
        command: PerfCommands,
    },

    /// List scheduled ingress sources and their durable cursor state (#573)
    ///
    /// Reads the compiled schema for each source's schedule and `run_as` ceiling,
    /// and — when a database is reachable — its cursor value, version, and staleness
    /// (seconds since the last advance). Leadership and last-fire are not reported
    /// here (an advisory lock has no visible holder, and the lease is released
    /// between ticks): watch `fraiseql_source_*` metrics and the poller logs for
    /// those. Always exits 0 — it is a report.
    #[command(after_help = "\
EXAMPLES:
    fraiseql sources
    fraiseql sources --schema schema.compiled.json
    fraiseql sources --db-url postgres://user:pass@host:5432/db
    fraiseql sources --json")]
    Sources {
        /// Path to schema.compiled.json.
        #[arg(long, default_value = "schema.compiled.json")]
        schema: std::path::PathBuf,

        /// PostgreSQL URL for cursor reads (defaults to `fraiseql.toml` /
        /// `DATABASE_URL`). Without one, definitions are listed with no cursor state.
        #[arg(long)]
        db_url: Option<String>,

        /// Output machine-readable JSON.
        #[arg(long)]
        json: bool,
    },

    /// Author-side function tooling (local test harness).
    #[cfg(feature = "functions-invoke")]
    #[command(subcommand)]
    Functions(FunctionsCommands),
}

/// `fraiseql functions` subcommands.
#[cfg(feature = "functions-invoke")]
#[derive(Subcommand)]
pub(crate) enum FunctionsCommands {
    /// Run a compiled function in a real V8 isolate against a fixture payload,
    /// with mocked host ops — the author's inner test loop.
    ///
    /// Exit codes: 0 = ran; 3 = the `when` predicate did not match (nothing would
    /// fire); 4 = the guest errored; 1 = a config/harness error.
    #[command(long_about = "\
Run a compiled function against a fixture payload in a real V8 isolate.

The module is loaded exactly as the server loads it (from the compiled schema's
module_dir); host ops are mocked so no live server, database, or network is needed.
Every host-op call the function makes is printed.

EXAMPLES:
    fraiseql functions invoke notifyApproved --payload event.json
    fraiseql functions invoke notifyApproved --payload event.json --explain
    fraiseql functions invoke syncDeal --payload deal.json \\
        --mock-http http.json --mock-query query.json")]
    Invoke {
        /// The function name (matches a definition in the compiled schema).
        name: String,

        /// Path to the fixture payload JSON. For after:mutation / after:capture:
        /// `{ \"event_kind\": \"update\", \"old\": {…}, \"new\": {…} }` (a bare
        /// object is treated as an insert's `new` image).
        #[arg(long)]
        payload: std::path::PathBuf,

        /// Path to schema.compiled.json.
        #[arg(long, default_value = "schema.compiled.json")]
        schema: std::path::PathBuf,

        /// Canned HTTP responses (JSON array of `{url_contains, method?, status?, body?}`);
        /// a request matching none fails loud.
        #[arg(long)]
        mock_http: Option<std::path::PathBuf>,

        /// Canned query responses (JSON array of `{query_contains?, response}`) for the
        /// `fraiseql_query` bridge; a query matching none fails loud.
        #[arg(long)]
        mock_query: Option<std::path::PathBuf>,

        /// Inject a fixed idempotency token the guest reads via the host op.
        #[arg(long)]
        idempotency_token: Option<String>,

        /// Print why the `when` predicates did or did not match this payload.
        #[arg(long)]
        explain: bool,
    },
}

/// `fraiseql perf` subcommands.
#[derive(Subcommand)]
pub(crate) enum PerfCommands {
    /// Flag mutations whose latency regressed between a baseline and a recent
    /// window, per `(object_type, modification_type)`.
    ///
    /// Only rows carrying the current `duration_calc_version` are compared, and
    /// latency is never aggregated across modification types — so a shift in the
    /// operation mix cannot mask a regression as a false improvement. Exits 0 even
    /// when regressions are found (it is a report); pass `--fail-on-regression`
    /// for CI gating.
    RegressionScan {
        /// PostgreSQL URL (defaults to `fraiseql.toml` / `DATABASE_URL`).
        #[arg(long, value_name = "DATABASE_URL")]
        database: Option<String>,

        /// Recent window size, in days.
        #[arg(long, default_value_t = 7)]
        recent_days: i64,

        /// Baseline window size (immediately before the recent window), in days.
        #[arg(long, default_value_t = 7)]
        baseline_days: i64,

        /// Minimum comparable samples required on each side; thinner groups are
        /// skipped rather than flagged.
        #[arg(long, default_value_t = 20)]
        min_samples: usize,

        /// Minimum p50 increase to flag, in percent.
        #[arg(long, default_value_t = 25.0)]
        threshold_pct: f64,

        /// Minimum absolute p50 increase to flag, in milliseconds (the noise floor).
        #[arg(long, default_value_t = 5.0)]
        min_delta_ms: f64,

        /// Restrict the scan to a single object_type.
        #[arg(long, value_name = "TYPE")]
        object_type: Option<String>,

        /// Exit non-zero when any regression is found (for CI gating).
        #[arg(long)]
        fail_on_regression: bool,
    },

    /// Ad-hoc forensic reads of the change-log.
    Explore {
        #[command(subcommand)]
        command: PerfExploreCommands,
    },
}

/// `fraiseql perf explore` subcommands — read-only views over comparable (v2)
/// change-log rows in a trailing window.
#[derive(Subcommand)]
pub(crate) enum PerfExploreCommands {
    /// The slowest individual mutations, slowest first.
    Slowest {
        /// PostgreSQL URL (defaults to `fraiseql.toml` / `DATABASE_URL`).
        #[arg(long, value_name = "DATABASE_URL")]
        database: Option<String>,

        /// Trailing window to scan, in days.
        #[arg(long, default_value_t = 7)]
        days: i32,

        /// Restrict to a single object_type.
        #[arg(long, value_name = "TYPE")]
        object_type: Option<String>,

        /// Maximum rows to return.
        #[arg(long, default_value_t = 20)]
        limit: usize,
    },

    /// `duration_ms` completeness (NULL / pre-fix rates), per operation.
    NullRate {
        /// PostgreSQL URL (defaults to `fraiseql.toml` / `DATABASE_URL`).
        #[arg(long, value_name = "DATABASE_URL")]
        database: Option<String>,

        /// Trailing window to scan, in days.
        #[arg(long, default_value_t = 7)]
        days: i32,

        /// Restrict to a single object_type.
        #[arg(long, value_name = "TYPE")]
        object_type: Option<String>,
    },

    /// Latency percentiles (p50/p95/p99/max), per operation.
    Summary {
        /// PostgreSQL URL (defaults to `fraiseql.toml` / `DATABASE_URL`).
        #[arg(long, value_name = "DATABASE_URL")]
        database: Option<String>,

        /// Trailing window to scan, in days.
        #[arg(long, default_value_t = 7)]
        days: i32,

        /// Restrict to a single object_type.
        #[arg(long, value_name = "TYPE")]
        object_type: Option<String>,
    },
}

#[derive(Subcommand)]
pub(crate) enum ValidateCommands {
    /// Validate that declared fact tables match database schema
    Facts {
        /// Schema.json file path
        #[arg(short, long, value_name = "SCHEMA")]
        schema: String,

        /// Database connection string
        // Long-only: `-d` is the global `--debug` short (#650).
        #[arg(long, value_name = "DATABASE_URL")]
        database: String,
    },
}

#[derive(Subcommand)]
pub(crate) enum GenerateClientCommands {
    /// Generate a TypeScript client (interfaces + typed query/mutation functions).
    Typescript {
        /// Path to schema.compiled.json (auto-detected from conventional
        /// locations if omitted).
        #[arg(long, value_name = "SCHEMA")]
        schema: Option<std::path::PathBuf>,

        /// Output directory for the generated client.
        #[arg(long, value_name = "DIR")]
        out: std::path::PathBuf,

        /// Overwrite an existing generated client in the output directory.
        #[arg(long, default_value_t = false)]
        force: bool,
    },

    /// Generate a Python client (TypedDicts + typed query/mutation functions;
    /// requires Python >= 3.12).
    Python {
        /// Path to schema.compiled.json (auto-detected from conventional
        /// locations if omitted).
        #[arg(long, value_name = "SCHEMA")]
        schema: Option<std::path::PathBuf>,

        /// Output directory for the generated client (becomes a Python package).
        #[arg(long, value_name = "DIR")]
        out: std::path::PathBuf,

        /// Overwrite an existing generated client in the output directory.
        #[arg(long, default_value_t = false)]
        force: bool,
    },

    /// Generate a Go client (structs + typed query/mutation functions; requires
    /// Go >= 1.21 for the Relay `Connection[T]`).
    Go {
        /// Path to schema.compiled.json (auto-detected from conventional
        /// locations if omitted).
        #[arg(long, value_name = "SCHEMA")]
        schema: Option<std::path::PathBuf>,

        /// Output directory for the generated client (becomes package
        /// `fraiseqlclient`).
        #[arg(long, value_name = "DIR")]
        out: std::path::PathBuf,

        /// Overwrite an existing generated client in the output directory.
        #[arg(long, default_value_t = false)]
        force: bool,
    },

    /// Generate a Rust client (serde types + typed query/mutation functions;
    /// depends only on serde and serde_json).
    Rust {
        /// Path to schema.compiled.json (auto-detected from conventional
        /// locations if omitted).
        #[arg(long, value_name = "SCHEMA")]
        schema: Option<std::path::PathBuf>,

        /// Output directory for the generated client (becomes a module tree with
        /// its own `mod.rs`).
        #[arg(long, value_name = "DIR")]
        out: std::path::PathBuf,

        /// Overwrite an existing generated client in the output directory.
        #[arg(long, default_value_t = false)]
        force: bool,
    },
}

#[derive(Subcommand)]
pub(crate) enum FederationCommands {
    /// Export federation graph
    Graph {
        /// Path to schema.compiled.json
        #[arg(value_name = "SCHEMA")]
        schema: String,

        /// Output format (json, dot, mermaid)
        #[arg(short, long, value_name = "FORMAT", default_value = "json")]
        format: String,
    },

    /// Validate subgraph composition
    Check {
        /// Path to local schema.compiled.json
        #[arg(value_name = "SCHEMA")]
        schema: String,

        /// Path to supergraph schema for composition validation
        #[arg(short, long, value_name = "SUPERGRAPH")]
        against: Option<String>,

        /// Output result as JSON
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand)]
pub(crate) enum IntrospectCommands {
    /// Introspect database for fact tables (tf_* tables)
    Facts {
        /// Database connection string
        // Long-only: `-d` is the global `--debug` short (#650).
        #[arg(long, value_name = "DATABASE_URL")]
        database: String,

        /// Output format (python, json)
        #[arg(short, long, value_name = "FORMAT", default_value = "python")]
        format: String,
    },
}

#[derive(Subcommand)]
pub(crate) enum SchemaCommands {
    /// Display field-level security metadata from a running server
    Metadata {
        /// Server base URL
        #[arg(
            short,
            long,
            value_name = "URL",
            default_value = "http://localhost:8080"
        )]
        server: String,

        /// Bearer token for authentication
        #[arg(short, long, value_name = "TOKEN")]
        token: Option<String>,
    },
}

#[derive(Subcommand)]
pub(crate) enum MigrateCommands {
    /// Apply pending migrations
    Up {
        /// Database connection URL
        #[arg(long, value_name = "DATABASE_URL")]
        database: Option<String>,

        /// Migration directory
        #[arg(long, value_name = "DIR")]
        dir: Option<String>,
    },

    /// Roll back migrations
    Down {
        /// Database connection URL
        #[arg(long, value_name = "DATABASE_URL")]
        database: Option<String>,

        /// Migration directory
        #[arg(long, value_name = "DIR")]
        dir: Option<String>,

        /// Number of migrations to roll back
        #[arg(long, default_value = "1")]
        steps: u32,
    },

    /// Show migration status
    Status {
        /// Database connection URL
        #[arg(long, value_name = "DATABASE_URL")]
        database: Option<String>,

        /// Migration directory
        #[arg(long, value_name = "DIR")]
        dir: Option<String>,
    },

    /// Create a new migration file
    Create {
        /// Migration name
        #[arg(value_name = "NAME")]
        name: String,

        /// Migration directory
        #[arg(long, value_name = "DIR")]
        dir: Option<String>,
    },

    /// Generate a new migration from schema diff
    ///
    /// Delegates to `confiture migrate generate`.
    /// Creates a timestamped migration file.
    Generate {
        /// Migration name
        #[arg(value_name = "NAME")]
        name: String,

        /// Migration directory
        #[arg(long, value_name = "DIR")]
        dir: Option<String>,
    },

    /// Validate migration files for naming, idempotency, and drift
    ///
    /// Delegates to `confiture migrate validate`.
    /// Checks naming conventions, idempotency, and schema drift.
    Validate {
        /// Migration directory
        #[arg(long, value_name = "DIR")]
        dir: Option<String>,
    },

    /// Pre-deploy safety check on pending migrations
    ///
    /// Delegates to `confiture migrate preflight`.
    /// Verifies reversibility, detects non-transactional statements, checks checksums.
    Preflight {
        /// Migration directory
        #[arg(long, value_name = "DIR")]
        dir: Option<String>,
    },
}