sqlite-graphrag 1.0.99

Persistent GraphRAG memory for Claude Code, Codex, Cursor, and 24+ AI agents in a single 19 MiB Rust binary. LLM-only and one-shot in v1.0.78: every `remember` / `ingest` spawns a headless claude code or codex subprocess (OAuth, no MCP, no hooks). v1.0.93: optional OpenRouter API embedding backend (~100-500ms vs 20-60s subprocess). No daemon. No ONNX runtime. No model download. Graph-native retrieval with FTS5 + cosine + multi-hop traversal. OAuth-only enforcement for LLM backends: API keys ABORT the spawn.
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
//! CLI argument structs and command surface (clap-based).
//!
//! Defines `Cli` and all subcommand enums; contains no business logic.

use crate::commands::*;
use crate::i18n::{current, Language};
use clap::{Parser, Subcommand};

/// Returns the maximum simultaneous invocations allowed by the CPU heuristic.
fn max_concurrency_ceiling() -> usize {
    std::thread::available_parallelism()
        .map(|n| n.get() * 2)
        .unwrap_or(8)
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum GraphExportFormat {
    Json,
    Dot,
    Mermaid,
    /// Stream one JSON object per entity, then one per edge, then a summary line.
    Ndjson,
}

/// v1.0.82 (GAP-003): LLM backend for embedding. Accepts `auto` (default —
/// detects `codex` or `claude` on the PATH), `codex` (forces codex exec), `claude`
/// (forces claude -p), or `none` (skips embedding; useful for tests).
#[derive(Copy, Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum LlmBackendChoice {
    Auto,
    Claude,
    Codex,
    Opencode,
    OpenRouter,
    None,
}

/// v1.0.93: embedding backend selector. Separate from `--llm-backend` which
/// controls enrichment (entity extraction, body enrichment) via subprocess.
/// `auto` tries OpenRouter if API key is available, falls back to LLM subprocess.
/// `openrouter` requires API key (exit 78 if absent).
/// `llm` forces subprocess (codex/claude/opencode) — legacy behaviour.
#[derive(Copy, Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum EmbeddingBackendChoice {
    Auto,
    Openrouter,
    Llm,
}

impl EmbeddingBackendChoice {
    /// v1.0.93: produces a fallback chain that prepends OpenRouter when
    /// the client is initialised. Falls back to the LLM subprocess chain.
    pub fn to_chain(self, llm_choice: LlmBackendChoice) -> Vec<crate::embedder::LlmBackendKind> {
        use crate::embedder::LlmBackendKind;
        match self {
            EmbeddingBackendChoice::Openrouter => vec![LlmBackendKind::OpenRouter],
            EmbeddingBackendChoice::Llm => llm_choice.to_chain(),
            EmbeddingBackendChoice::Auto => {
                if crate::embedder::is_openrouter_initialized() {
                    let mut chain = vec![LlmBackendKind::OpenRouter];
                    chain.extend(llm_choice.to_chain());
                    chain
                } else {
                    llm_choice.to_chain()
                }
            }
        }
    }
}

impl LlmBackendChoice {
    /// v1.0.82 (GAP-003): converts the CLI choice into an ordered chain
    /// of backends that `embedder::embed_with_fallback` iterates. The first
    /// element of the chain is the preferred backend; subsequent elements
    /// are fallbacks used when the preferred one fails with `LlmBackendError`.
    ///
    /// `Auto` produces `[Codex, Claude, None]` — codex is the default since v1.0.76+,
    /// claude is the fallback if codex fails (OAuth contention, quota), and
    /// `None` lets `embed_with_fallback` return an empty vector when
    /// `skip_on_failure` is active.
    pub fn to_chain(self) -> Vec<crate::embedder::LlmBackendKind> {
        use crate::embedder::LlmBackendKind;
        match self {
            LlmBackendChoice::Codex => vec![LlmBackendKind::Codex, LlmBackendKind::None],
            LlmBackendChoice::Claude => vec![LlmBackendKind::Claude, LlmBackendKind::None],
            LlmBackendChoice::Opencode => vec![
                LlmBackendKind::Opencode,
                LlmBackendKind::Codex,
                LlmBackendKind::Claude,
                LlmBackendKind::None,
            ],
            LlmBackendChoice::OpenRouter => vec![
                LlmBackendKind::OpenRouter,
                LlmBackendKind::Codex,
                LlmBackendKind::None,
            ],
            LlmBackendChoice::None => vec![LlmBackendKind::None],
            LlmBackendChoice::Auto => parse_fallback_chain(
                &std::env::var("SQLITE_GRAPHRAG_LLM_FALLBACK")
                    .unwrap_or_else(|_| "codex,claude,none".to_string()),
            ),
        }
    }
}

fn parse_fallback_chain(s: &str) -> Vec<crate::embedder::LlmBackendKind> {
    use crate::embedder::LlmBackendKind;
    let mut chain: Vec<LlmBackendKind> = s
        .split(',')
        .filter_map(|tok| match tok.trim().to_ascii_lowercase().as_str() {
            "codex" => Some(LlmBackendKind::Codex),
            "claude" | "claude-code" => Some(LlmBackendKind::Claude),
            "opencode" => Some(LlmBackendKind::Opencode),
            "openrouter" => Some(LlmBackendKind::OpenRouter),
            "none" => Some(LlmBackendKind::None),
            _ => {
                tracing::warn!(
                    token = tok.trim(),
                    "unknown backend in --llm-fallback, skipping"
                );
                Option::None
            }
        })
        .collect();
    if chain.is_empty() {
        chain = vec![
            LlmBackendKind::Codex,
            LlmBackendKind::Claude,
            LlmBackendKind::None,
        ];
    }
    chain
}

#[derive(Parser)]
#[command(name = "sqlite-graphrag")]
#[command(version)]
#[command(about = "Local GraphRAG memory for LLMs in a single SQLite file")]
#[command(arg_required_else_help = true)]
#[command(after_help = "DATABASE PATH (GAP-SG-32):\n  \
    `--db` is a PER-SUBCOMMAND flag, so it must come AFTER the subcommand:\n    \
    sqlite-graphrag remember --db ./graphrag.sqlite --name mem --type note ...\n  \
    Placing it before the subcommand (e.g. `sqlite-graphrag --db x.sqlite remember`) is rejected.\n  \
    For a position-independent path, set the canonical env var instead:\n    \
    SQLITE_GRAPHRAG_DB_PATH=./graphrag.sqlite sqlite-graphrag remember --name mem ...")]
pub struct Cli {
    /// Maximum number of simultaneous CLI invocations allowed (default: 4).
    ///
    /// Caps the counting semaphore used for CLI concurrency slots. The value must
    /// stay within [1, 2×nCPUs]. Values above the ceiling are rejected with exit 2.
    #[arg(long, global = true, value_name = "N")]
    pub max_concurrency: Option<usize>,

    /// Wait up to SECONDS for a free concurrency slot before giving up (exit 75).
    ///
    /// Useful in retrying agent pipelines: the process polls every 500 ms until a
    /// slot opens or the timeout expires. Default: 300s (5 minutes).
    #[arg(long, global = true, value_name = "SECONDS")]
    pub wait_lock: Option<u64>,

    /// Skip the available-memory check before loading the model.
    ///
    /// Exclusive use in automated tests where real allocation does not occur.
    #[arg(long, global = true, hide = true, default_value_t = false)]
    pub skip_memory_guard: bool,

    /// v1.0.83 (ADR-0041): strict env-clear mode for compliance environments.
    ///
    /// When enabled, the LLM subprocess receives ONLY `PATH` — no
    /// `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_BASE_URL`, `OPENAI_BASE_URL`
    /// or other custom-provider credentials are forwarded. Defaults to
    /// the standard v1.0.83 whitelist that preserves custom-provider
    /// credentials (ADR-0041). Honors env var
    /// `SQLITE_GRAPHRAG_STRICT_ENV_CLEAR=1` when set.
    #[arg(
        long,
        global = true,
        hide = true,
        default_value_t = false,
        value_parser = clap::builder::BoolishValueParser::new(),
        env = "SQLITE_GRAPHRAG_STRICT_ENV_CLEAR"
    )]
    pub strict_env_clear: bool,

    /// v1.0.84 (ADR-0042 / GAP-002): resolve and print the LLM backend that
    /// WOULD be invoked for embedding (binary path + model + flavour),
    /// then exit 0 without executing the subprocess. Useful for CI
    /// audit and sanity-check of `--llm-backend` before long sessions.
    ///
    /// Honors env var `SQLITE_GRAPHRAG_DRY_RUN_BACKEND=1` when set.
    #[arg(
        long,
        global = true,
        hide = true,
        default_value_t = false,
        value_parser = clap::builder::BoolishValueParser::new(),
        env = "SQLITE_GRAPHRAG_DRY_RUN_BACKEND"
    )]
    pub dry_run_backend: bool,

    /// Language for human-facing stderr messages. Accepts `en` or `pt`.
    ///
    /// Without the flag, detection falls back to `SQLITE_GRAPHRAG_LANG` and then
    /// `LC_ALL`/`LANG`. JSON stdout stays deterministic and identical across
    /// languages; only human-facing strings are affected.
    #[arg(long, global = true, value_enum, value_name = "LANG")]
    pub lang: Option<crate::i18n::Language>,

    /// Time zone for `*_iso` fields in JSON output (for example `America/Sao_Paulo`).
    ///
    /// Accepts any IANA time zone name. Without the flag, it falls back to
    /// `SQLITE_GRAPHRAG_DISPLAY_TZ`; if unset, UTC is used. Integer epoch fields
    /// are not affected.
    #[arg(long, global = true, value_name = "IANA")]
    pub tz: Option<chrono_tz::Tz>,

    /// Increase logging verbosity (-v=info, -vv=debug, -vvv=trace).
    ///
    /// Overrides `SQLITE_GRAPHRAG_LOG_LEVEL` env var when present. Logs are emitted
    /// to stderr; JSON stdout is unaffected.
    #[arg(short = 'v', long, global = true, action = clap::ArgAction::Count)]
    pub verbose: u8,

    /// v1.0.75 (G21 solution): extraction backend selector. Accepts
    /// `llm` (default), `embedding` (legacy), `none`, or `both` (composite).
    /// The `llm` backend invokes claude code / codex CLI headless to extract
    /// entities and relationships; `embedding` is a permanent stub since
    /// v1.0.79 (legacy fastembed pipeline removed) that returns a clear
    /// migration error.
    #[arg(long, global = true, value_name = "KIND", default_value = "llm")]
    pub extraction_backend: Option<String>,

    /// v1.0.79 (G42/S1): embedding dimensionality override (default 64).
    ///
    /// Precedence: this flag > `SQLITE_GRAPHRAG_EMBEDDING_DIM` env var >
    /// the `dim` recorded in the database `schema_meta` > 64. Existing
    /// databases keep their recorded dimensionality automatically; use
    /// this flag only to migrate a corpus to a new dimensionality
    /// (followed by `enrich --operation re-embed`). Range: [8, 4096].
    #[arg(long, global = true, value_name = "N", value_parser = clap::value_parser!(u64).range(8..=4096))]
    pub embedding_dim: Option<u64>,

    /// v1.0.82 (GAP-003) / v1.0.84 (ADR-0042): LLM backend for embedding.
    /// Accepts `auto` (detects via PATH, codex-first), `codex` (forces
    /// `codex exec`), `claude` (forces `claude -p`; since v1.0.84 does NOT fall back to
    /// codex — emits `AppError::Validation` if `claude` is absent),
    /// `opencode` (forces `opencode run`), or `none`
    /// (skips embedding; useful for tests). Honors the env var
    /// `SQLITE_GRAPHRAG_LLM_BACKEND`.
    #[arg(long, global = true, value_enum, default_value_t = LlmBackendChoice::Auto, env = "SQLITE_GRAPHRAG_LLM_BACKEND")]
    pub llm_backend: LlmBackendChoice,

    /// v1.0.82 (GAP-003): model to invoke on the chosen backend.
    /// Honors the env var `SQLITE_GRAPHRAG_LLM_MODEL`. The default depends
    /// on the backend (codex: `gpt-5.5`; claude: `claude-sonnet-4-6`).
    #[arg(
        long,
        global = true,
        value_name = "MODEL",
        env = "SQLITE_GRAPHRAG_LLM_MODEL"
    )]
    pub llm_model: Option<String>,

    /// v1.0.82 (GAP-003): path to the `claude` binary (overrides
    /// PATH detection). Honors the env var `SQLITE_GRAPHRAG_CLAUDE_BINARY`.
    #[arg(
        long,
        global = true,
        value_name = "PATH",
        env = "SQLITE_GRAPHRAG_CLAUDE_BINARY"
    )]
    pub claude_binary: Option<std::path::PathBuf>,

    /// v1.0.89 (GAP-1): path to the `codex` binary (overrides
    /// PATH detection). Honors the env var `SQLITE_GRAPHRAG_CODEX_BINARY`.
    #[arg(
        long,
        global = true,
        value_name = "PATH",
        env = "SQLITE_GRAPHRAG_CODEX_BINARY"
    )]
    pub codex_binary: Option<std::path::PathBuf>,

    /// v1.0.90 (GAP-OPENCODE-001): path to the `opencode` binary (overrides
    /// PATH detection). Honors the env var `SQLITE_GRAPHRAG_OPENCODE_BINARY`.
    #[arg(
        long,
        global = true,
        value_name = "PATH",
        env = "SQLITE_GRAPHRAG_OPENCODE_BINARY"
    )]
    pub opencode_binary: Option<std::path::PathBuf>,

    /// v1.0.82 (GAP-005): chain of LLM backends tried in order
    /// when the primary fails. Default `codex,claude,none`. Honors
    /// the env var `SQLITE_GRAPHRAG_LLM_FALLBACK`.
    #[arg(
        long,
        global = true,
        default_value = "codex,claude,none",
        env = "SQLITE_GRAPHRAG_LLM_FALLBACK"
    )]
    pub llm_fallback: String,

    /// v1.0.82 (GAP-005): persists with a NULL embedding when all
    /// backends in the chain fail. The memory stays in `pending_embeddings`
    /// for reprocessing via `embedding retry`. Honors the env var
    /// `SQLITE_GRAPHRAG_SKIP_EMBEDDING_ON_FAILURE`.
    #[arg(
        long,
        global = true,
        default_value_t = false,
        value_parser = clap::builder::BoolishValueParser::new(),
        env = "SQLITE_GRAPHRAG_SKIP_EMBEDDING_ON_FAILURE"
    )]
    pub skip_embedding_on_failure: bool,

    /// v1.0.82 (GAP-004): host-wide limit of concurrent LLM
    /// subprocesses. Default derived from `ncpus`. Honors the env var
    /// `SQLITE_GRAPHRAG_LLM_MAX_HOST_CONCURRENCY`.
    #[arg(
        long,
        global = true,
        value_name = "N",
        env = "SQLITE_GRAPHRAG_LLM_MAX_HOST_CONCURRENCY"
    )]
    pub llm_max_host_concurrency: Option<u32>,

    /// v1.0.82 (GAP-004): seconds to wait for a free LLM slot
    /// before failing with exit 75. Default 30s. Honors the env var
    /// `SQLITE_GRAPHRAG_LLM_SLOT_WAIT_SECS`.
    #[arg(
        long,
        global = true,
        value_name = "SECONDS",
        env = "SQLITE_GRAPHRAG_LLM_SLOT_WAIT_SECS"
    )]
    pub llm_slot_wait_secs: Option<u64>,

    /// v1.0.82 (GAP-004): if set, fails immediately (exit 75)
    /// when no LLM slot is free. Honors the env var
    /// `SQLITE_GRAPHRAG_LLM_SLOT_NO_WAIT`.
    #[arg(
        long,
        global = true,
        default_value_t = false,
        value_parser = clap::builder::BoolishValueParser::new(),
        env = "SQLITE_GRAPHRAG_LLM_SLOT_NO_WAIT"
    )]
    pub llm_slot_no_wait: bool,

    /// v1.0.93: embedding backend selector. `auto` tries OpenRouter API if key
    /// available, falls back to LLM subprocess. `openrouter` requires API key.
    /// `llm` forces subprocess. Honra env var `SQLITE_GRAPHRAG_EMBEDDING_BACKEND`.
    #[arg(long, global = true, value_enum, default_value_t = EmbeddingBackendChoice::Auto, env = "SQLITE_GRAPHRAG_EMBEDDING_BACKEND")]
    pub embedding_backend: EmbeddingBackendChoice,

    /// v1.0.93: embedding model for the OpenRouter API. Required when
    /// `--embedding-backend openrouter`. Honors env var `SQLITE_GRAPHRAG_EMBEDDING_MODEL`.
    #[arg(
        long,
        global = true,
        value_name = "MODEL",
        env = "SQLITE_GRAPHRAG_EMBEDDING_MODEL"
    )]
    pub embedding_model: Option<String>,

    /// v1.0.93: OpenRouter API key (prefer env var or config.toml over CLI flag
    /// to avoid shell history exposure). Honra env var `OPENROUTER_API_KEY`.
    #[arg(
        long,
        global = true,
        value_name = "KEY",
        hide = true,
        env = "OPENROUTER_API_KEY"
    )]
    pub openrouter_api_key: Option<String>,

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

#[cfg(test)]
mod json_only_format_tests {
    use super::Cli;
    use clap::Parser;

    #[test]
    fn restore_accepts_only_format_json() {
        assert!(Cli::try_parse_from([
            "sqlite-graphrag",
            "restore",
            "--name",
            "mem",
            "--version",
            "1",
            "--format",
            "json",
        ])
        .is_ok());

        assert!(Cli::try_parse_from([
            "sqlite-graphrag",
            "restore",
            "--name",
            "mem",
            "--version",
            "1",
            "--format",
            "text",
        ])
        .is_err());
    }

    #[test]
    fn hybrid_search_accepts_only_format_json() {
        assert!(Cli::try_parse_from([
            "sqlite-graphrag",
            "hybrid-search",
            "query",
            "--format",
            "json",
        ])
        .is_ok());

        assert!(Cli::try_parse_from([
            "sqlite-graphrag",
            "hybrid-search",
            "query",
            "--format",
            "markdown",
        ])
        .is_err());
    }

    #[test]
    fn remember_recall_rename_vacuum_json_only() {
        assert!(Cli::try_parse_from([
            "sqlite-graphrag",
            "remember",
            "--name",
            "mem",
            "--type",
            "project",
            "--description",
            "desc",
            "--format",
            "json",
        ])
        .is_ok());
        assert!(Cli::try_parse_from([
            "sqlite-graphrag",
            "remember",
            "--name",
            "mem",
            "--type",
            "project",
            "--description",
            "desc",
            "--format",
            "text",
        ])
        .is_err());

        assert!(
            Cli::try_parse_from(["sqlite-graphrag", "recall", "query", "--format", "json",])
                .is_ok()
        );
        assert!(
            Cli::try_parse_from(["sqlite-graphrag", "recall", "query", "--format", "text",])
                .is_err()
        );

        assert!(Cli::try_parse_from([
            "sqlite-graphrag",
            "rename",
            "--name",
            "old",
            "--new-name",
            "new",
            "--format",
            "json",
        ])
        .is_ok());
        assert!(Cli::try_parse_from([
            "sqlite-graphrag",
            "rename",
            "--name",
            "old",
            "--new-name",
            "new",
            "--format",
            "markdown",
        ])
        .is_err());

        assert!(Cli::try_parse_from(["sqlite-graphrag", "vacuum", "--format", "json",]).is_ok());
        assert!(Cli::try_parse_from(["sqlite-graphrag", "vacuum", "--format", "text",]).is_err());
    }
}

impl Cli {
    /// Validates concurrency flags and returns a localised descriptive error if invalid.
    ///
    /// Requires that `crate::i18n::init()` has already been called (happens before this
    /// function in the `main` flow). In English it emits EN messages; in Portuguese it emits PT.
    pub fn validate_flags(&self) -> Result<(), String> {
        if let Some(n) = self.max_concurrency {
            if n == 0 {
                return Err(match current() {
                    Language::English => "--max-concurrency must be >= 1".to_string(),
                    Language::Portuguese => "--max-concurrency deve ser >= 1".to_string(),
                });
            }
            let teto = max_concurrency_ceiling();
            if n > teto {
                return Err(match current() {
                    Language::English => format!(
                        "--max-concurrency {n} exceeds the ceiling of {teto} (2×nCPUs) on this system"
                    ),
                    Language::Portuguese => format!(
                        "--max-concurrency {n} excede o teto de {teto} (2×nCPUs) neste sistema"
                    ),
                });
            }
        }
        Ok(())
    }
}

impl Commands {
    /// Returns true for subcommands that load the ONNX model locally.
    pub fn is_embedding_heavy(&self) -> bool {
        matches!(
            self,
            Self::Init(_)
                | Self::Remember(_)
                | Self::RememberBatch(_)
                | Self::Recall(_)
                | Self::HybridSearch(_)
                | Self::DeepResearch(_)
        )
    }

    pub fn uses_cli_slot(&self) -> bool {
        true
    }

    /// Read-only / no-embedding subcommands that MUST run without an embedding
    /// API key. `init` warms a best-effort smoke test internally and degrades to
    /// `ok_no_embedding` when the backend is unreachable; the `enrich` queue
    /// inspectors (`--status` / `--list-dead` / `--requeue-dead` /
    /// `--prune-dead-orphans`) never embed and never call the LLM. The eager
    /// OpenRouter key preflight in `main` must skip its hard-fail for these.
    pub fn tolerates_missing_embedding_key(&self) -> bool {
        match self {
            Self::Init(_) => true,
            Self::Enrich(args) => {
                args.status || args.list_dead || args.requeue_dead || args.prune_dead_orphans
            }
            _ => false,
        }
    }
}

/// GAP-E2E-010 (v1.0.89): `codex-models` accepts `--json` as a no-op so
/// agents that append `--json` to every subcommand never see clap errors.
/// The handler in `main.rs` always emits JSON on stdout; this flag is
/// accepted and ignored for parity with the rest of the CLI surface.
#[derive(Debug, clap::Args)]
pub struct CodexModelsArgs {
    /// No-op; JSON is always emitted on stdout by `codex-models`.
    #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
    pub json: bool,
}

#[derive(Subcommand)]
pub enum Commands {
    /// Initialize database and download embedding model
    #[command(after_long_help = "EXAMPLES:\n  \
        # Initialize in current directory (default behavior)\n  \
        sqlite-graphrag init\n\n  \
        # Initialize at a specific path\n  \
        sqlite-graphrag init --db /path/to/graphrag.sqlite\n\n  \
        # Initialize using SQLITE_GRAPHRAG_HOME env var\n  \
        SQLITE_GRAPHRAG_HOME=/data sqlite-graphrag init\n\n\
        NOTES:\n  \
        - `init` is OPTIONAL: any subsequent CRUD command auto-initializes graphrag.sqlite if missing.\n  \
        - As a side effect, `init` warms a smoke-test embedding via the LLM-only one-shot pipeline.")]
    Init(init::InitArgs),
    /// Save a memory with optional entity graph
    #[command(after_long_help = "EXAMPLES:\n  \
        # Inline body\n  \
        sqlite-graphrag remember --name onboarding --type user --description \"intro\" --body \"hello\"\n\n  \
        # Body from file\n  \
        sqlite-graphrag remember --name doc1 --type document --description \"...\" --body-file ./README.md\n\n  \
        # Body from stdin (pipe)\n  \
        cat README.md | sqlite-graphrag remember --name doc1 --type document --description \"...\" --body-stdin\n\n  \
        # Enable automatic URL extraction (URL-regex only since v1.0.79; GLiNER removed)\n  \
        sqlite-graphrag remember --name rich --type note --description \"...\" --body \"...\" --enable-ner")]
    Remember(remember::RememberArgs),
    /// Batch-create memories from NDJSON stdin (one invocation, one slot)
    #[command(after_long_help = "EXAMPLES:\n  \
        # Batch create from NDJSON\n  \
        cat memories.ndjson | sqlite-graphrag remember-batch --force-merge --json\n\n  \
        # Atomic batch\n  \
        cat memories.ndjson | sqlite-graphrag remember-batch --transaction --json")]
    RememberBatch(remember_batch::RememberBatchArgs),
    /// Bulk-ingest every file under a directory as separate memories (NDJSON output)
    Ingest(ingest::IngestArgs),
    /// Search memories semantically
    #[command(after_long_help = "EXAMPLES:\n  \
        # Top 10 semantic matches (default)\n  \
        sqlite-graphrag recall \"agent memory\"\n\n  \
        # Top 3 only\n  \
        sqlite-graphrag recall \"agent memory\" -k 3\n\n  \
        # Search across all namespaces\n  \
        sqlite-graphrag recall \"agent memory\" --all-namespaces\n\n  \
        # Disable graph traversal (vector-only)\n  \
        sqlite-graphrag recall \"agent memory\" --no-graph")]
    Recall(recall::RecallArgs),
    /// Read a memory by exact name
    Read(read::ReadArgs),
    /// List memories with filters
    List(list::ListArgs),
    /// Soft-delete a memory
    Forget(forget::ForgetArgs),
    /// Permanently delete soft-deleted memories
    Purge(purge::PurgeArgs),
    /// Rename a memory preserving history
    Rename(rename::RenameArgs),
    /// Edit a memory's body or description
    Edit(edit::EditArgs),
    /// List all versions of a memory
    History(history::HistoryArgs),
    /// Restore a memory to a previous version
    Restore(restore::RestoreArgs),
    /// Search using hybrid vector + full-text search
    #[command(after_long_help = "EXAMPLES:\n  \
        # Hybrid search combining KNN + FTS5 BM25 with RRF\n  \
        sqlite-graphrag hybrid-search \"agent memory architecture\"\n\n  \
        # Custom weights for vector vs full-text components\n  \
        sqlite-graphrag hybrid-search \"agent\" --weight-vec 0.7 --weight-fts 0.3")]
    HybridSearch(hybrid_search::HybridSearchArgs),
    /// Show database health
    Health(health::HealthArgs),
    /// Apply pending schema migrations
    Migrate(migrate::MigrateArgs),
    /// Resolve namespace precedence for the current invocation
    NamespaceDetect(namespace_detect::NamespaceDetectArgs),
    /// Run PRAGMA optimize on the database
    Optimize(optimize::OptimizeArgs),
    /// Show database statistics
    Stats(stats::StatsArgs),
    /// Create a checkpointed copy safe for file sync
    SyncSafeCopy(sync_safe_copy::SyncSafeCopyArgs),
    /// Back up the database using the SQLite Online Backup API
    Backup(backup::BackupArgs),
    /// Run VACUUM after checkpointing the WAL
    Vacuum(vacuum::VacuumArgs),
    /// Create an explicit relationship between two entities
    Link(link::LinkArgs),
    /// Remove a specific relationship between two entities
    Unlink(unlink::UnlinkArgs),
    /// Deep parallel multi-hop GraphRAG research
    #[command(name = "deep-research")]
    DeepResearch(deep_research::DeepResearchArgs),
    /// List memories connected via the entity graph
    Related(related::RelatedArgs),
    /// Export a graph snapshot in json, dot or mermaid
    Graph(graph_export::GraphArgs),
    /// Export memories as NDJSON (one JSON line per memory, plus a summary line)
    Export(export::ExportArgs),
    /// FTS5 full-text search index management (rebuild or check)
    Fts(fts::FtsArgs),
    /// Vector index maintenance (orphan detection, purge, stats) — G39
    Vec(vec::VecArgs),
    /// List codex OAuth models accepted by ChatGPT Pro (G33).
    ///
    /// GAP-E2E-010 (v1.0.89): accepts `--json` as a no-op (JSON is always
    /// emitted on stdout) so the flag never breaks agent pipelines that
    /// append `--json` to every invocation.
    #[command(name = "codex-models")]
    CodexModels(CodexModelsArgs),
    /// Bulk-delete all relationships of a given type (e.g. mentions)
    PruneRelations(prune_relations::PruneRelationsArgs),
    /// Remove NER bindings (memory_entities rows) for an entity or all entities
    #[command(name = "prune-ner")]
    PruneNer(prune_ner::PruneNerArgs),
    /// Inspect and manage cross-process LLM slot semaphore (GAP-004, v1.0.82)
    Slots(slots::SlotsArgs),
    /// Inspect and manage the `remember` checkpoint queue (GAP-001, v1.0.82)
    Pending(pending::PendingArgs),
    /// Health and per-entry inspection of the pending-embeddings queue (GAP-005, v1.0.82)
    Embedding(embedding::EmbeddingArgs),
    /// Batch operations over the pending-embeddings queue (GAP-005, v1.0.82)
    #[command(name = "pending-embeddings")]
    PendingEmbeddings(pending_embeddings::PendingEmbeddingsArgs),
    /// Remove entities that have no memories and no relationships
    CleanupOrphans(cleanup_orphans::CleanupOrphansArgs),
    /// List entities linked to a specific memory
    MemoryEntities(memory_entities::MemoryEntitiesArgs),
    /// Manage cached resources (embedding models, etc.)
    Cache(cache::CacheArgs),
    /// Delete an entity and all its relationships from the graph
    #[command(name = "delete-entity")]
    DeleteEntity(delete_entity::DeleteEntityArgs),
    /// Reclassify one entity or a batch of entities to a new type
    Reclassify(reclassify::ReclassifyArgs),
    /// Rename an entity preserving all relationships and memory bindings
    #[command(name = "rename-entity")]
    RenameEntity(rename_entity::RenameEntityArgs),
    /// Merge multiple source entities into a single target entity
    #[command(name = "merge-entities")]
    MergeEntities(merge_entities::MergeEntitiesArgs),
    /// Enrich graph memories and entities using an LLM provider
    Enrich(enrich::EnrichArgs),
    /// Reclassify relationship types across the graph using rules or LLM judgment
    #[command(name = "reclassify-relation")]
    ReclassifyRelation(reclassify_relation::ReclassifyRelationArgs),
    /// Normalize entity names (deduplicate, kebab-case, merge near-duplicates)
    #[command(name = "normalize-entities")]
    NormalizeEntities(normalize_entities::NormalizeEntitiesArgs),
    /// Generate shell completions for Bash, Zsh, Fish, PowerShell, or Elvish
    Completions(completions::CompletionsArgs),
    #[command(name = "debug-schema", hide = true)]
    DebugSchema(debug_schema::DebugSchemaArgs),
    /// Manage API keys and diagnose provider configuration (v1.0.93)
    Config(config_cmd::ConfigArgs),
}
// FIX-1 (v1.0.89): manual `Debug` impl so test panic messages that print
// `{:?}` on a captured `Commands` variant compile without requiring every
// contained subcommand arg struct to derive `Debug`. The Debug output is
// only used in test assertions for diagnostic messages; we emit the variant
// name only — arg payload is intentionally omitted.
impl std::fmt::Debug for Commands {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            Self::Init(_) => "Init",
            Self::Health(_) => "Health",
            Self::Stats(_) => "Stats",
            Self::List(_) => "List",
            Self::Read(_) => "Read",
            Self::Edit(_) => "Edit",
            Self::Rename(_) => "Rename",
            Self::Restore(_) => "Restore",
            Self::History(_) => "History",
            Self::Forget(_) => "Forget",
            Self::Purge(_) => "Purge",
            Self::Remember(_) => "Remember",
            Self::RememberBatch(_) => "RememberBatch",
            Self::Recall(_) => "Recall",
            Self::HybridSearch(_) => "HybridSearch",
            Self::Enrich(_) => "Enrich",
            Self::Ingest(_) => "Ingest",
            Self::Optimize(_) => "Optimize",
            Self::Migrate(_) => "Migrate",
            Self::SyncSafeCopy(_) => "SyncSafeCopy",
            Self::Backup(_) => "Backup",
            Self::Vacuum(_) => "Vacuum",
            Self::Link(_) => "Link",
            Self::Unlink(_) => "Unlink",
            Self::DeepResearch(_) => "DeepResearch",
            Self::Related(_) => "Related",
            Self::Graph(_) => "Graph",
            Self::Export(_) => "Export",
            Self::Fts(_) => "Fts",
            Self::Vec(_) => "Vec",
            Self::CodexModels(_) => "CodexModels",
            Self::PruneRelations(_) => "PruneRelations",
            Self::PruneNer(_) => "PruneNer",
            Self::Slots(_) => "Slots",
            Self::Pending(_) => "Pending",
            Self::Embedding(_) => "Embedding",
            Self::PendingEmbeddings(_) => "PendingEmbeddings",
            Self::CleanupOrphans(_) => "CleanupOrphans",
            Self::MemoryEntities(_) => "MemoryEntities",
            Self::Cache(_) => "Cache",
            Self::DeleteEntity(_) => "DeleteEntity",
            Self::Reclassify(_) => "Reclassify",
            Self::RenameEntity(_) => "RenameEntity",
            Self::ReclassifyRelation(_) => "ReclassifyRelation",
            Self::NormalizeEntities(_) => "NormalizeEntities",
            Self::MergeEntities(_) => "MergeEntities",
            Self::NamespaceDetect(_) => "NamespaceDetect",
            Self::Completions(_) => "Completions",
            Self::DebugSchema(_) => "DebugSchema",
            Self::Config(_) => "Config",
        };
        f.write_str(name)
    }
}

#[derive(Copy, Clone, Debug, Default, clap::ValueEnum)]
pub enum MemoryType {
    User,
    Feedback,
    Project,
    Reference,
    Decision,
    Incident,
    Skill,
    #[default]
    Document,
    Note,
}

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

    #[test]
    fn command_heavy_detects_init_and_embeddings() {
        let init = Cli::try_parse_from(["sqlite-graphrag", "init"]).expect("parse init");
        assert!(init
            .command
            .as_ref()
            .is_some_and(|c| c.is_embedding_heavy()));

        let remember = Cli::try_parse_from([
            "sqlite-graphrag",
            "remember",
            "--name",
            "test-memory",
            "--type",
            "project",
            "--description",
            "desc",
        ])
        .expect("parse remember");
        assert!(remember
            .command
            .as_ref()
            .is_some_and(|c| c.is_embedding_heavy()));

        let recall =
            Cli::try_parse_from(["sqlite-graphrag", "recall", "query"]).expect("parse recall");
        assert!(recall
            .command
            .as_ref()
            .is_some_and(|c| c.is_embedding_heavy()));

        let hybrid = Cli::try_parse_from(["sqlite-graphrag", "hybrid-search", "query"])
            .expect("parse hybrid");
        assert!(hybrid
            .command
            .as_ref()
            .is_some_and(|c| c.is_embedding_heavy()));
    }

    #[test]
    fn command_light_does_not_mark_stats() {
        let stats = Cli::try_parse_from(["sqlite-graphrag", "stats"]).expect("parse stats");
        assert!(!stats
            .command
            .as_ref()
            .is_some_and(|c| c.is_embedding_heavy()));
    }
}

impl MemoryType {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::User => "user",
            Self::Feedback => "feedback",
            Self::Project => "project",
            Self::Reference => "reference",
            Self::Decision => "decision",
            Self::Incident => "incident",
            Self::Skill => "skill",
            Self::Document => "document",
            Self::Note => "note",
        }
    }
}

/// GAP-SG-31/33/34/35/30: parse-time contracts for the Fase G clap fixes.
#[cfg(test)]
mod fase_g_parsing_tests {
    use super::Cli;
    use clap::Parser;

    /// GAP-SG-31(b): `enrich --status` parses without --operation/--mode.
    #[test]
    fn enrich_status_optional_operation_and_mode() {
        assert!(
            Cli::try_parse_from(["sqlite-graphrag", "enrich", "--status"]).is_ok(),
            "--status alone must not require --operation/--mode"
        );
        assert!(
            Cli::try_parse_from(["sqlite-graphrag", "enrich", "--list-dead"]).is_ok(),
            "--list-dead is read-only and must not require --operation/--mode"
        );
        // Write path still requires both: bare `enrich` is rejected.
        assert!(
            Cli::try_parse_from(["sqlite-graphrag", "enrich"]).is_err(),
            "bare enrich (no status/list-dead/requeue-dead) must require --operation/--mode"
        );
        // Full write invocation still parses.
        assert!(Cli::try_parse_from([
            "sqlite-graphrag",
            "enrich",
            "--operation",
            "memory-bindings",
            "--mode",
            "openrouter",
        ])
        .is_ok());
    }

    /// GAP-SG-34(c): `config doctor --json` parses (no-op flag accepted).
    #[test]
    fn config_doctor_accepts_json() {
        assert!(Cli::try_parse_from(["sqlite-graphrag", "config", "doctor", "--json"]).is_ok());
        assert!(Cli::try_parse_from(["sqlite-graphrag", "config", "list-keys", "--json"]).is_ok());
    }

    /// GAP-SG-33(d): a hyphen-led --description value is accepted, not parsed
    /// as a flag.
    #[test]
    fn remember_description_allows_leading_hyphen() {
        assert!(Cli::try_parse_from([
            "sqlite-graphrag",
            "remember",
            "--name",
            "mem",
            "--type",
            "note",
            "--description",
            "- bullet description",
        ])
        .is_ok());
    }

    /// GAP-SG-35(e): `remember-batch --llm-parallelism N` parses.
    #[test]
    fn remember_batch_accepts_llm_parallelism() {
        assert!(Cli::try_parse_from([
            "sqlite-graphrag",
            "remember-batch",
            "--llm-parallelism",
            "4"
        ])
        .is_ok());
    }

    /// GAP-SG-30: --graph-file combines with a body source but conflicts with
    /// the other graph-input flags.
    #[test]
    fn remember_graph_file_combines_with_body_but_conflicts_with_graph_stdin() {
        assert!(
            Cli::try_parse_from([
                "sqlite-graphrag",
                "remember",
                "--name",
                "mem",
                "--type",
                "note",
                "--body",
                "inline body",
                "--graph-file",
                "/tmp/graph.json",
            ])
            .is_ok(),
            "--body + --graph-file must coexist"
        );
        assert!(
            Cli::try_parse_from([
                "sqlite-graphrag",
                "remember",
                "--name",
                "mem",
                "--type",
                "note",
                "--graph-file",
                "/tmp/graph.json",
                "--graph-stdin",
            ])
            .is_err(),
            "--graph-file conflicts with --graph-stdin"
        );
    }
}