oxilite-cli 0.10.0

oxilite command line: load, query, and a SPARQL HTTP endpoint compatible with `oxigraph serve`
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
//! `oxilite`: an interactive SPARQL shell (the default command), load and query a store from the
//! command line, or serve it over the SPARQL 1.1 protocol with the same routes as
//! `oxigraph serve` (`/query`, `/update`, `/store`).
//!
//! The store is a SQLite file (bundled SQLite), the same file through a SQLite shared library
//! (`--library`), or a D1 database behind the local sidecar (`--d1-sidecar`, used by the
//! benchmarks).
//!
// @lat: [[architecture#Command line and HTTP endpoint]]

mod db;
mod registry;
mod shell;
mod studio;
mod versioning;

use db::QueryFlags;
use registry::RegistryCommand;
use versioning::VersioningCommand;

use clap::{Parser, Subcommand};
use db::Db;
use oxilite::io::RdfFormat;
use std::sync::Arc;
use std::time::Instant;
use tiny_http::{Header, Method, Request, Response, Server};

#[derive(Parser)]
#[command(
    name = "oxilite",
    version,
    about = "oxilite: an Oxigraph-compatible SPARQL store on SQLite",
    long_about = "oxilite: an Oxigraph-compatible SPARQL store on SQLite.\n\n\
        Without a command, opens an interactive SPARQL shell on DATABASE (a SQLite file, created \
        with the schema if missing) or on a transient in-memory store.",
    args_conflicts_with_subcommands = true
)]
struct Args {
    #[command(subcommand)]
    command: Option<Command>,
    /// The shell's SQLite database file (created if missing; in memory when omitted).
    database: Option<String>,
    #[command(flatten)]
    location: Location,
}

#[derive(clap::Args, Clone, Default)]
struct Location {
    /// SQLite database file (created if missing).
    #[arg(long, short)]
    location: Option<String>,
    /// Load this SQLite shared library instead of the bundled SQLite.
    #[arg(long)]
    library: Option<String>,
    /// Use Turso (SQLite rewritten in Rust) instead of the bundled SQLite: vector indexes and
    /// search become available.
    #[arg(long)]
    turso: bool,
    /// Use the D1 database of a local sidecar (`testsuite/d1-sidecar`) at this URL.
    #[arg(long)]
    d1_sidecar: Option<String>,
    /// Create the store without the graph index (fewer writes if you only use the default graph).
    #[arg(long)]
    no_graph_index: bool,
    /// Create the full-text index over string literals (for `oxl:textMatch`).
    #[arg(long)]
    text_index: bool,
    /// Versioning of a new store: `off` (default), `stamped` (a store clock and the tick that
    /// added each quad) or `log` (an immutable change log: history and time travel). An existing
    /// store keeps its level; change it with `oxilite versioning set`.
    #[arg(long, value_name = "LEVEL")]
    versioning: Option<String>,
    /// With `--versioning log`: also index the change log by predicate and object (faster
    /// as-of queries, two more rows written per change).
    #[arg(long)]
    as_of_index: bool,
    /// With `--versioning stamped` or `log`: index the tick that added each quad (faster
    /// "added since" queries, one more row written per quad).
    #[arg(long)]
    stamp_index: bool,
    /// Author recorded on the commits of this command's writes (versioned stores).
    #[arg(long)]
    author: Option<String>,
    /// Message recorded on the commits of this command's writes (versioned stores).
    #[arg(long, short = 'm')]
    message: Option<String>,
    /// Do not install the system graphs (the oxilite vocabulary in `<oxilite:vocabulary>`,
    /// the registry's description in `<oxilite:schema>`) in a new, blank store.
    #[arg(long)]
    no_system_graphs: bool,
}

#[derive(Subcommand)]
enum Command {
    /// Serves the store over the SPARQL 1.1 protocol.
    Serve {
        #[command(flatten)]
        location: Location,
        #[arg(long, short, default_value = "127.0.0.1:7879")]
        bind: String,
        /// Worker threads.
        #[arg(long, default_value_t = 8)]
        threads: usize,
        /// How every query matches (reasoning, inferences, schema graphs).
        #[command(flatten)]
        flags: QueryFlags,
    },
    /// Bulk-loads RDF files, then refreshes planner statistics.
    Load {
        #[command(flatten)]
        location: Location,
        /// Files to load; the format comes from the extension unless `--format` is given.
        #[arg(long, short, required = true, num_args = 1..)]
        file: Vec<String>,
        #[arg(long)]
        format: Option<String>,
    },
    /// Runs a SPARQL query and prints the results.
    Query {
        #[command(flatten)]
        location: Location,
        #[arg(long, short)]
        query: String,
        /// Read the store as it was at this version: `HEAD~2`, `#42` (a tick) or
        /// `@2026-09-01T12:00:00Z` (versioning `log`).
        #[arg(long, value_name = "VERSION")]
        as_of: Option<String>,
        /// Results format (json, xml, csv, tsv, or an RDF format for graph results).
        #[arg(long, default_value = "json")]
        results_format: String,
        #[command(flatten)]
        flags: QueryFlags,
    },
    /// Prints the SQL a query compiles to, with the planner's notes.
    Explain {
        #[command(flatten)]
        location: Location,
        #[arg(long, short)]
        query: String,
        /// Compile the query against this version of the store (see `query --as-of`).
        #[arg(long, value_name = "VERSION")]
        as_of: Option<String>,
        #[command(flatten)]
        flags: QueryFlags,
    },
    /// Runs a SPARQL update.
    Update {
        #[command(flatten)]
        location: Location,
        #[arg(long, short)]
        update: String,
    },
    /// Runs a Datalog program: recursive rules with stratified negation.
    ///
    /// The program is read from `--program`, or from the file named by `--file`, or from
    /// standard input when neither is given.
    Datalog {
        #[command(flatten)]
        location: Location,
        /// The program text.
        #[arg(long, short, conflicts_with = "file")]
        program: Option<String>,
        /// A file holding the program.
        #[arg(long, short)]
        file: Option<String>,
        /// Print the strata, the strategy per recursive component and the SQL, and run nothing.
        #[arg(long)]
        explain: bool,
        /// Store what the program derives as inferences instead of returning its goal.
        #[arg(long, conflicts_with = "explain")]
        materialize: bool,
        /// Run the program on this version of the store (like an `@version` directive).
        #[arg(long, value_name = "VERSION", conflicts_with = "materialize")]
        as_of: Option<String>,
    },
    /// Runs Notation3 rules with the eyeron reasoner and prints what follows as N-Triples.
    ///
    /// The rules are read from `--program`, or from the file named by `--file`, or from standard
    /// input. A run reads every graph but the system graphs (or the `--graph`s), and only the
    /// predicates the rule bodies use. `--materialize` stores the conclusions as inferences
    /// instead, replacing the producer's earlier ones; query them with `--inferred`.
    N3 {
        #[command(flatten)]
        location: Location,
        /// The N3 rule text.
        #[arg(long, short, conflicts_with = "file")]
        program: Option<String>,
        /// A file holding the rules.
        #[arg(long, short)]
        file: Option<String>,
        /// Store the conclusions as inferences instead of printing them.
        #[arg(long)]
        materialize: bool,
        /// The producer the conclusions are stored under.
        #[arg(long, default_value = "n3")]
        producer: String,
        /// Read only this graph (`DEFAULT` or an IRI); repeatable.
        #[arg(long = "graph", value_name = "GRAPH")]
        graphs: Vec<String>,
        /// Also read other producers' materialized inferences.
        #[arg(long)]
        inferred: bool,
        /// Load the whole scope instead of only the predicates the rules read.
        #[arg(long)]
        no_prune: bool,
        /// Print eyeron's proof after the conclusions.
        #[arg(long, conflicts_with = "materialize")]
        proof: bool,
        /// The instant `time:localTime` reports, in milliseconds since the Unix epoch.
        #[arg(long, value_name = "MILLIS")]
        now: Option<i64>,
        /// eyeron's fixpoint step limit.
        #[arg(long)]
        max_iterations: Option<usize>,
    },
    /// Runs a λProlog (ELPI) program with lean-elpi over the store.
    ///
    /// Programs read the store with `ox.triple S P O` and `ox.quad S P O G`, where terms are
    /// `(iri "…")`, `(str "…")`, `(num N)`, `(dbl F)`, `(lang "…" "tag")`, `(lit "…" "datatype")`
    /// and `(bnode "…")`. Give a `--goal` to print its solutions, `--check` to list what
    /// `ox.violation Severity Name Message Focus` reports (exit code 1 on any `error`), or
    /// `--materialize` to store what `ox.conclude (triple S P O)` concludes. Needs a build with
    /// the `elpi` feature and the native libleanelpi.
    Elpi {
        #[command(flatten)]
        location: Location,
        /// The program text.
        #[arg(long, short, conflicts_with = "file")]
        program: Option<String>,
        /// A file holding the program.
        #[arg(long, short)]
        file: Option<String>,
        /// The goal to solve, e.g. `anc (iri "http://example.org/ada") Y`.
        #[arg(long, short, required_unless_present_any = ["check", "materialize"])]
        goal: Option<String>,
        /// List the violations the program reports.
        #[arg(long, conflicts_with_all = ["goal", "materialize"])]
        check: bool,
        /// Store the program's conclusions as inferences.
        #[arg(long, conflicts_with = "goal")]
        materialize: bool,
        /// The producer the conclusions are stored under.
        #[arg(long, default_value = "elpi")]
        producer: String,
        /// Read only this graph (`DEFAULT` or an IRI); repeatable.
        #[arg(long = "graph", value_name = "GRAPH")]
        graphs: Vec<String>,
        /// Also read other producers' materialized inferences.
        #[arg(long)]
        inferred: bool,
        /// At most this many solutions.
        #[arg(long)]
        limit: Option<usize>,
        /// Resolution steps the run may take.
        #[arg(long)]
        fuel: Option<u64>,
    },
    /// Runs a Synalog program (the Datalog-family language for AI agents) and prints the rows
    /// of one predicate.
    ///
    /// The store reads as tables: `triples(subject, predicate, object, kind, datatype, lang,
    /// graph)`, plus those the program declares with `# @table NAME <IRI>` and
    /// `# @class NAME <IRI>`. The program is read from `--program`, or from the file named by
    /// `--file`, or from standard input when neither is given.
    Synalog {
        #[command(flatten)]
        location: Location,
        /// The predicate whose rows to print.
        predicate: String,
        /// The program text.
        #[arg(long, short, conflicts_with = "file")]
        program: Option<String>,
        /// A file holding the program.
        #[arg(long, short)]
        file: Option<String>,
        /// Print the SQL the predicate compiles to on the store, and run nothing.
        #[arg(long)]
        sql: bool,
        /// Print the SQL for this engine (duckdb, psql, bigquery, trino, presto, databricks,
        /// sqlite) without opening a store.
        #[arg(long, conflicts_with_all = ["sql", "as_of", "union_graph", "inferred"])]
        engine: Option<String>,
        /// At most this many rows.
        #[arg(long)]
        limit: Option<u64>,
        /// Skip this many rows.
        #[arg(long)]
        offset: Option<u64>,
        /// Read every graph, not only the default graph.
        #[arg(long)]
        union_graph: bool,
        /// Also read materialized inferences.
        #[arg(long)]
        inferred: bool,
        /// Run the program on this version of the store.
        #[arg(long, value_name = "VERSION")]
        as_of: Option<String>,
    },
    /// The schema registry: which graphs hold ontologies, SHACL shapes or ShEx schemas.
    Registry {
        #[command(subcommand)]
        action: RegistryCommand,
    },
    /// Computes the OWL 2 RL closure into the inference table (query it with `--inferred`).
    Materialize {
        #[command(flatten)]
        location: Location,
        /// Remove every materialized inference instead.
        #[arg(long)]
        clear: bool,
    },
    /// Versioning: the level, the history, changes, diffs, purges and D1 migrations.
    Versioning {
        #[command(subcommand)]
        action: VersioningCommand,
    },
    /// Prints the schema as a SQL script, e.g. for `wrangler d1 migrations` (the store options
    /// choose the indexes and the versioning level).
    Schema {
        /// Without the graph index.
        #[arg(long)]
        no_graph_index: bool,
        /// With the full-text index.
        #[arg(long)]
        text_index: bool,
        /// Versioning level: off (default), stamped or log.
        #[arg(long, value_name = "LEVEL", default_value = "off")]
        versioning: String,
        /// With `log`: the as-of index.
        #[arg(long)]
        as_of_index: bool,
        /// With `stamped` or `log`: the stamp index.
        #[arg(long)]
        stamp_index: bool,
        /// Also insert the system graphs (the oxilite vocabulary and the registry's description).
        #[arg(long)]
        system_graphs: bool,
    },
    /// Refreshes planner statistics and the reasoning closure.
    Optimize {
        #[command(flatten)]
        location: Location,
    },
    /// Checks a project like oxilite studio does: load errors, rule errors, SHACL results and the
    /// tests in `oxilite.toml`. Exits with status 1 when anything fails.
    Check {
        /// The project root (default: the current directory).
        #[arg(default_value = ".")]
        root: String,
        /// Print the report as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Serves the studio's tools (query, schema, validate, why) to agents over the Model Context
    /// Protocol on standard input and output.
    Mcp {
        /// The project root to load like oxilite studio's Project store (default: here).
        #[arg(long)]
        root: Option<String>,
        /// Open this store file read-only instead of loading a project.
        #[arg(long, conflicts_with = "root")]
        location: Option<String>,
    },
    /// Runs the language server behind oxilite studio (LSP over standard input and output).
    StudioServer {
        /// Scratch store location (default `<workspace>/.oxilite/studio.sqlite`; `:memory:` works).
        #[arg(long)]
        store: Option<String>,
    },
}

fn main() {
    let args = Args::parse();
    let result = match args.command {
        Some(command) => run(command),
        None => {
            let mut location = args.location;
            if let Some(database) = args.database {
                location.location = Some(database);
            }
            match shell::run(location) {
                Ok(0) => Ok(()),
                Ok(code) => std::process::exit(code),
                Err(e) => Err(e),
            }
        }
    };
    if let Err(e) = result {
        eprintln!("error: {e}");
        std::process::exit(1);
    }
}

fn run(command: Command) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    match command {
        Command::Serve {
            location,
            bind,
            threads,
            flags,
        } => {
            let db = Arc::new(Db::open(&location)?);
            let server = Arc::new(Server::http(&bind).map_err(|e| e.to_string())?);
            eprintln!("oxilite listening on http://{bind}/ (query endpoint /query, update endpoint /update)");
            let workers: Vec<_> = (0..threads.max(1))
                .map(|_| {
                    let (server, db) = (Arc::clone(&server), Arc::clone(&db));
                    let flags = flags.clone();
                    std::thread::spawn(move || {
                        for request in server.incoming_requests() {
                            handle(&db, &flags, request);
                        }
                    })
                })
                .collect();
            for w in workers {
                let _ = w.join();
            }
            Ok(())
        }
        Command::Load {
            location,
            file,
            format,
        } => {
            let db = Db::open(&location)?;
            for f in file {
                let format = match &format {
                    Some(m) => parse_format(m)?,
                    None => RdfFormat::from_extension(f.rsplit('.').next().unwrap_or_default())
                        .ok_or_else(|| format!("unknown format of {f}"))?,
                };
                let start = Instant::now();
                let data = std::fs::read(&f)?;
                db.load(format, &data, None, true)?;
                eprintln!("loaded {f} in {:.2}s", start.elapsed().as_secs_f64());
            }
            Ok(())
        }
        Command::Query {
            location,
            query,
            results_format,
            as_of,
            flags,
        } => {
            let db = Db::open(&location)?;
            let out = db.query_at(&query, &[], &[], as_of.as_deref(), &flags)?;
            print!(
                "{}",
                oxilite_core::json::output_to_format(&out, &results_format)?
            );
            Ok(())
        }
        Command::Explain {
            location,
            query,
            as_of,
            flags,
        } => {
            println!(
                "{}",
                Db::open(&location)?.explain_at(&query, as_of.as_deref(), &flags)?
            );
            Ok(())
        }
        Command::Update { location, update } => Ok(Db::open(&location)?.update(&update, &[])?),
        Command::Datalog {
            location,
            program,
            file,
            explain,
            materialize,
            as_of,
        } => {
            let source = read_program(program, file)?;
            let db = Db::open(&location)?;
            if explain {
                println!("{}", db.explain_datalog(&source)?);
                return Ok(());
            }
            if materialize {
                let stats = db.datalog_materialize(&source)?;
                println!(
                    "{} inferred triple(s) from {} relation(s)",
                    stats.inferred, stats.relations
                );
                return Ok(());
            }
            let r = db.datalog_at(&source, as_of.as_deref())?;
            println!("{}", r.variables.join("\t"));
            for row in &r.rows {
                let line: Vec<String> = row
                    .iter()
                    .map(|c| c.as_ref().map(ToString::to_string).unwrap_or_default())
                    .collect();
                println!("{}", line.join("\t"));
            }
            Ok(())
        }
        Command::N3 {
            location,
            program,
            file,
            materialize,
            producer,
            graphs,
            inferred,
            no_prune,
            proof,
            now,
            max_iterations,
        } => {
            let rules = read_program(program, file)?;
            let db = Db::open(&location)?;
            let options = oxilite::n3::Options {
                graphs: if graphs.is_empty() {
                    None
                } else {
                    Some(
                        graphs
                            .iter()
                            .map(|g| db::parse_graph(g))
                            .collect::<Result<_, _>>()?,
                    )
                },
                include_inferred: inferred,
                prune: !no_prune,
                producer,
                now,
                proof,
                limits: oxilite::n3::Limits {
                    max_iterations,
                    ..Default::default()
                },
                ..Default::default()
            };
            if materialize {
                let stats = db.n3_materialize(&rules, &options)?;
                println!(
                    "{} inferred triple(s) from {} statement(s) (producer {})",
                    stats.inferred, stats.loaded, stats.producer
                );
                if stats.unstorable > 0 {
                    eprintln!("{} conclusion(s) could not be stored", stats.unstorable);
                }
                return Ok(());
            }
            let r = db.n3_reason(&rules, &options)?;
            for t in &r.derived {
                println!("{t} .");
            }
            for u in &r.unstorable {
                eprintln!("not storable: {}", u.trim());
            }
            if let Some(f) = &r.fuse {
                eprintln!("{}", f.trim());
            }
            if !r.complete {
                let mut why = r.limits.clone();
                why.extend(r.errors.iter().cloned());
                eprintln!("incomplete: {}", why.join("; "));
            }
            if let Some(p) = &r.proof {
                println!("\n# proof\n{p}");
            }
            eprintln!(
                "{} conclusion(s) from {} statement(s)",
                r.derived.len(),
                r.loaded
            );
            Ok(())
        }
        Command::Elpi {
            location,
            program,
            file,
            goal,
            check,
            materialize,
            producer,
            graphs,
            inferred,
            limit,
            fuel,
        } => run_elpi(ElpiArgs {
            location,
            program,
            file,
            goal,
            check,
            materialize,
            producer,
            graphs,
            inferred,
            limit,
            fuel,
        }),
        Command::Synalog {
            location,
            predicate,
            program,
            file,
            sql,
            engine,
            limit,
            offset,
            union_graph,
            inferred,
            as_of,
        } => {
            let source = read_program(program, file)?;
            if let Some(engine) = engine {
                println!(
                    "{}",
                    oxilite::synalog::compile_for_engine(
                        &source, &predicate, &engine, limit, offset
                    )?
                );
                return Ok(());
            }
            let db = Db::open(&location)?;
            if sql {
                println!("{}", db.synalog_sql(&source, &predicate)?);
                return Ok(());
            }
            let options = oxilite::synalog::Options {
                union_default_graph: union_graph,
                include_inferred: inferred,
                limit,
                offset,
                as_of,
                ..Default::default()
            };
            let r = db.synalog(&source, &predicate, &options)?;
            println!("{}", r.columns.join("\t"));
            for row in &r.rows {
                let line: Vec<String> = row
                    .iter()
                    .map(|v| match v {
                        oxilite::synalog::SqlValue::Null => String::new(),
                        oxilite::synalog::SqlValue::Integer(i) => i.to_string(),
                        oxilite::synalog::SqlValue::Real(r) => r.to_string(),
                        oxilite::synalog::SqlValue::Text(t) => t.clone(),
                    })
                    .collect();
                println!("{}", line.join("\t"));
            }
            Ok(())
        }
        Command::Optimize { location } => Ok(Db::open(&location)?.optimize()?),
        Command::Versioning { action } => versioning::run(action),
        Command::Registry { action } => registry::run(action),
        Command::Materialize { location, clear } => {
            let db = Db::open(&location)?;
            if clear {
                db.clear_inferences()?;
            } else {
                let start = Instant::now();
                let n = db.materialize()?;
                eprintln!(
                    "{n} inferred triple(s) in {:.2}s",
                    start.elapsed().as_secs_f64()
                );
            }
            Ok(())
        }
        Command::Schema {
            no_graph_index,
            text_index,
            versioning,
            as_of_index,
            stamp_index,
            system_graphs,
        } => {
            let options = oxilite::StoreOptions {
                graph_index: !no_graph_index,
                text_index,
                versioning: versioning.parse()?,
                as_of_index,
                stamp_index,
                system_graphs,
            };
            print!("{}", oxilite_core::schema::schema_sql(&options));
            Ok(())
        }
        Command::StudioServer { store } => studio::run(store),
        Command::Mcp { root, location } => studio::mcp::serve(root.map(Into::into), location),
        Command::Check { root, json } => {
            let (passed, report) = studio::check::check(root.into())?;
            if json {
                println!("{}", serde_json::to_string_pretty(&report)?);
            } else {
                print!("{}", studio::check::render(&report));
            }
            if !passed {
                std::process::exit(1);
            }
            Ok(())
        }
    }
}

/// A program given inline, in a file, or on standard input.
#[cfg_attr(not(feature = "elpi"), allow(dead_code))]
struct ElpiArgs {
    location: Location,
    program: Option<String>,
    file: Option<String>,
    goal: Option<String>,
    check: bool,
    materialize: bool,
    producer: String,
    graphs: Vec<String>,
    inferred: bool,
    limit: Option<usize>,
    fuel: Option<u64>,
}

#[cfg(not(feature = "elpi"))]
fn run_elpi(_: ElpiArgs) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    Err(
        "this oxilite was built without ELPI: install it with `--features elpi`, \
         with LEANELPI_DIST pointing at a libleanelpi build"
            .into(),
    )
}

// @tg: implements:: [[openspec:elpi-programs#Command line]] {since: "2026-11-03"}
#[cfg(feature = "elpi")]
fn run_elpi(a: ElpiArgs) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let program = read_program(a.program, a.file)?;
    let db = Db::open(&a.location)?;
    let mut options = oxilite::elpi::Options {
        graphs: if a.graphs.is_empty() {
            None
        } else {
            Some(
                a.graphs
                    .iter()
                    .map(|g| db::parse_graph(g))
                    .collect::<Result<_, _>>()?,
            )
        },
        include_inferred: a.inferred,
        producer: a.producer,
        ..Default::default()
    };
    if let Some(l) = a.limit {
        options.limit = l;
    }
    if let Some(f) = a.fuel {
        options.fuel = f;
    }
    if a.check {
        let violations = db.elpi_check(&program, &options)?;
        for v in &violations {
            let focus: Vec<String> = v.focus.iter().map(ToString::to_string).collect();
            println!(
                "{}\t{}\t{}\t{}",
                v.severity,
                v.name,
                v.message,
                focus.join(" ")
            );
        }
        eprintln!("{} violation(s)", violations.len());
        if violations.iter().any(|v| v.severity == "error") {
            std::process::exit(1);
        }
        return Ok(());
    }
    if a.materialize {
        let stats = db.elpi_materialize(&program, &options)?;
        println!(
            "{} inferred triple(s) (producer {}, {} row(s) read)",
            stats.inferred, stats.producer, stats.rows_read
        );
        if stats.unstorable > 0 {
            eprintln!("{} conclusion(s) could not be stored", stats.unstorable);
        }
        return Ok(());
    }
    let goal = a.goal.ok_or("give --goal, --check or --materialize")?;
    let r = db.elpi_query(&program, &goal, &options)?;
    let vars: Vec<String> = r
        .solutions
        .first()
        .map(|s| s.bindings.keys().cloned().collect())
        .unwrap_or_default();
    if vars.is_empty() {
        // a closed goal: it holds or it does not
        println!("{}", !r.solutions.is_empty());
        return Ok(());
    }
    println!("{}", vars.join("\t"));
    for s in &r.solutions {
        let cells: Vec<String> = vars
            .iter()
            .map(|v| match s.bindings.get(v) {
                Some(oxilite::elpi::Binding::Term(t)) => t.to_string(),
                // ELPI prints long values over several lines: keep one row per solution
                Some(oxilite::elpi::Binding::Value(x)) => {
                    x.split_whitespace().collect::<Vec<_>>().join(" ")
                }
                None => String::new(),
            })
            .collect();
        println!("{}", cells.join("\t"));
    }
    eprintln!(
        "{} solution(s){}, {} row(s) read",
        r.solutions.len(),
        if r.exhausted { "" } else { " (limit reached)" },
        r.rows_read
    );
    Ok(())
}

fn read_program(
    program: Option<String>,
    file: Option<String>,
) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
    if let Some(p) = program {
        return Ok(p);
    }
    if let Some(f) = file {
        return Ok(std::fs::read_to_string(f)?);
    }
    let mut buf = String::new();
    std::io::Read::read_to_string(&mut std::io::stdin(), &mut buf)?;
    if buf.trim().is_empty() {
        return Err("no program given: use --program, --file, or pipe one in".into());
    }
    Ok(buf)
}

pub(crate) fn parse_format(media: &str) -> Result<RdfFormat, String> {
    let m = media.split(';').next().unwrap_or_default().trim();
    RdfFormat::from_media_type(m)
        .or_else(|| RdfFormat::from_extension(m))
        .ok_or_else(|| format!("unsupported RDF format {media}"))
}

fn header(request: &Request, name: &str) -> Option<String> {
    request
        .headers()
        .iter()
        .find(|h| h.field.to_string().eq_ignore_ascii_case(name))
        .map(|h| h.value.as_str().to_string())
}

fn respond(request: Request, status: u16, content_type: &str, body: String) {
    let r = Response::from_string(body)
        .with_status_code(status)
        .with_header(Header::from_bytes("Content-Type", content_type).expect("valid header"));
    let _ = request.respond(r);
}

/// Picks the response media type from the `Accept` header.
fn negotiate(accept: Option<&str>, graph: bool) -> &'static str {
    let candidates: &[&str] = if graph {
        &[
            "application/n-triples",
            "text/turtle",
            "application/rdf+xml",
            "application/n-quads",
            "application/trig",
        ]
    } else {
        &[
            "application/sparql-results+json",
            "application/sparql-results+xml",
            "text/csv",
            "text/tab-separated-values",
        ]
    };
    if let Some(accept) = accept {
        for part in accept.split(',') {
            let m = part.split(';').next().unwrap_or_default().trim();
            if let Some(c) = candidates.iter().find(|c| **c == m) {
                return c;
            }
            if m == "application/json" && !graph {
                return "application/sparql-results+json";
            }
            if m == "application/xml" && !graph {
                return "application/sparql-results+xml";
            }
        }
    }
    candidates[if graph { 1 } else { 0 }]
}

fn handle(db: &Db, flags: &QueryFlags, mut request: Request) {
    let url = request.url().to_string();
    let (path, query_string) = url.split_once('?').unwrap_or((url.as_str(), ""));
    let mut params: Vec<(String, String)> = form_urlencoded::parse(query_string.as_bytes())
        .into_owned()
        .collect();
    let content_type = header(&request, "Content-Type").unwrap_or_default();
    let mut body = Vec::new();
    if request.method() == &Method::Post {
        if let Err(e) = request.as_reader().read_to_end(&mut body) {
            return respond(request, 400, "text/plain", e.to_string());
        }
    }
    let form = content_type.starts_with("application/x-www-form-urlencoded");
    if form {
        params.extend(form_urlencoded::parse(&body).into_owned());
    }
    let get = |k: &str| params.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
    let all = |k: &str| {
        params
            .iter()
            .filter(|(n, _)| n == k)
            .map(|(_, v)| v.clone())
            .collect::<Vec<_>>()
    };
    let result: Result<(u16, String, String), String> = (|| match (request.method(), path) {
        (Method::Get | Method::Post, "/query") => {
            let query = match get("query") {
                Some(q) => q,
                None if content_type.starts_with("application/sparql-query") => {
                    String::from_utf8(body.clone()).map_err(|e| e.to_string())?
                }
                None => return Err("missing query".into()),
            };
            let out = db
                .query_at(
                    &query,
                    &all("default-graph-uri"),
                    &all("named-graph-uri"),
                    get("version").as_deref(),
                    flags,
                )
                .map_err(|e| e.to_string())?;
            let graph = matches!(out, oxilite_core::QueryOutput::Graph(_));
            let media = negotiate(header(&request, "Accept").as_deref(), graph);
            let text =
                oxilite_core::json::output_to_format(&out, media).map_err(|e| e.to_string())?;
            Ok((200, media.to_string(), text))
        }
        (Method::Post, "/update") => {
            let update = match get("update") {
                Some(u) => u,
                None if content_type.starts_with("application/sparql-update") => {
                    String::from_utf8(body.clone()).map_err(|e| e.to_string())?
                }
                None => return Err("missing update".into()),
            };
            db.update(&update, &all("using-graph-uri"))
                .map_err(|e| e.to_string())?;
            Ok((204, "text/plain".into(), String::new()))
        }
        (Method::Post, "/store") => {
            let format = parse_format(&content_type)?;
            let graph = get("graph");
            let bulk = params.iter().any(|(n, _)| n == "no_transaction");
            db.load(format, &body, graph.as_deref(), bulk)
                .map_err(|e| e.to_string())?;
            Ok((204, "text/plain".into(), String::new()))
        }
        (Method::Get, "/") => Ok((
            200,
            "text/plain".into(),
            "oxilite SPARQL endpoint: /query, /update, /store\n".into(),
        )),
        _ => Ok((404, "text/plain".into(), "not found\n".into())),
    })();
    match result {
        Ok((status, media, text)) => respond(request, status, &media, text),
        Err(e) => respond(request, 400, "text/plain", e),
    }
}