ontoindex-cli 0.8.0

CLI for OntoIndex ontology indexing and querying
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
use anyhow::{bail, Context, Result};
use clap::{Parser, Subcommand, ValueEnum};
use ontoindex_catalog::{CatalogStats, IndexBuilder, OntologyCatalog};
use ontoindex_query::{
    query_catalog,
    sparql::to_json as sparql_to_json,
    sparql_catalog,
    sql::{to_csv as sql_to_csv, to_json as sql_to_json},
};
use ontoindex_reasoner::{classify, explain, ExplanationRequest, ReasonerId, WorkspaceInputLoader};
use ontoindex_refactor::{
    apply_refactor_plan_checked, find_usages, preview_extract_module, preview_migrate_namespace,
    preview_move_entity, preview_rename_iri, RefactorPlan,
};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

#[derive(Parser)]
#[command(
    name = "ontoindex",
    version,
    about = "Local-first ontology index and query engine (OntoCode v0.8)"
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Scan and index ontology files in a workspace
    Index {
        /// Workspace directory
        #[arg(default_value = ".")]
        workspace: PathBuf,
        /// Output format
        #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
        format: OutputFormat,
    },
    /// Run a SQL-like query over ontology tables
    Query {
        /// Workspace directory
        workspace: PathBuf,
        /// SQL query string
        sql: String,
        #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
        format: OutputFormat,
    },
    /// Run a SPARQL query over indexed triples
    Sparql {
        /// Workspace directory
        workspace: PathBuf,
        /// SPARQL query string
        query: String,
        #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
        format: OutputFormat,
    },
    /// Validate ontology files in a workspace
    Validate {
        /// Workspace directory
        #[arg(default_value = ".")]
        workspace: PathBuf,
    },
    /// Inspect catalog statistics for a workspace
    Inspect {
        /// Workspace directory
        #[arg(default_value = ".")]
        workspace: PathBuf,
        #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
        format: OutputFormat,
    },
    /// Apply Turtle patch operations from a JSON file
    Patch {
        /// Turtle document to patch
        document: PathBuf,
        /// JSON file containing an array of patch operations
        patch_file: PathBuf,
        /// Preview changes without writing to disk
        #[arg(long)]
        preview: bool,
    },
    /// Classify ontologies in a workspace with a reasoner profile
    Classify {
        /// Workspace directory
        #[arg(default_value = ".")]
        workspace: PathBuf,
        /// Reasoner profile: el, rl, rdfs (dl/auto require OntoLogos 1.0)
        #[arg(long, default_value = "el")]
        profile: String,
        /// Emit profile-detection warnings
        #[arg(long, default_value_t = true)]
        auto_profile: bool,
        #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
        format: OutputFormat,
    },
    /// Explain unsatisfiability for a class IRI
    Explain {
        /// Workspace directory
        #[arg(default_value = ".")]
        workspace: PathBuf,
        /// Class IRI to explain
        #[arg(long)]
        class: String,
        /// Reasoner profile
        #[arg(long, default_value = "el")]
        profile: String,
        #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
        format: OutputFormat,
    },
    /// Run ROBOT CLI subcommands (validate, merge, report)
    Robot {
        #[command(subcommand)]
        command: RobotCommands,
    },
    /// Workspace refactoring (rename, migrate, move, extract)
    Refactor {
        #[command(subcommand)]
        command: RefactorCommands,
    },
}

#[derive(Subcommand)]
enum RefactorCommands {
    /// List usages of an entity IRI across the workspace
    Usages {
        workspace: PathBuf,
        iri: String,
        #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
        format: OutputFormat,
    },
    /// Rename an entity IRI across Turtle files
    Rename {
        workspace: PathBuf,
        #[arg(long)]
        from: String,
        #[arg(long)]
        to: String,
        #[arg(long)]
        preview: bool,
        #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
        format: OutputFormat,
    },
    /// Migrate a namespace base IRI across the workspace
    MigrateNamespace {
        workspace: PathBuf,
        #[arg(long)]
        from: String,
        #[arg(long)]
        to: String,
        #[arg(long)]
        preview: bool,
        #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
        format: OutputFormat,
    },
    /// Move an entity block to another Turtle file
    Move {
        workspace: PathBuf,
        iri: String,
        #[arg(long)]
        to: PathBuf,
        #[arg(long)]
        preview: bool,
        #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
        format: OutputFormat,
    },
    /// Extract selected entities into a new module file
    Extract {
        workspace: PathBuf,
        #[arg(long, value_delimiter = ',')]
        entities: Vec<String>,
        #[arg(long)]
        out: PathBuf,
        #[arg(long)]
        leave_stub: bool,
        #[arg(long)]
        preview: bool,
        #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
        format: OutputFormat,
    },
}

#[derive(Subcommand)]
enum RobotCommands {
    /// Run `robot validate`
    Validate {
        /// Ontology file or directory
        path: PathBuf,
        #[arg(long)]
        robot_path: Option<String>,
    },
    /// Run `robot merge`
    Merge {
        #[arg(long, required = true)]
        inputs: Vec<PathBuf>,
        #[arg(long)]
        output: PathBuf,
        #[arg(long)]
        robot_path: Option<String>,
    },
    /// Run `robot report`
    Report {
        /// Ontology file or directory
        path: PathBuf,
        #[arg(long)]
        report: PathBuf,
        #[arg(long)]
        robot_path: Option<String>,
    },
}

#[derive(Clone, Copy, ValueEnum)]
enum OutputFormat {
    Text,
    Json,
    Csv,
}

fn main() -> Result<()> {
    let cli = Cli::parse();
    match cli.command {
        Commands::Index { workspace, format } => {
            let catalog = build_catalog(&workspace)?;
            print_stats(&catalog.data().stats(), format)?;
        }
        Commands::Query { workspace, sql, format } => {
            let catalog = build_catalog(&workspace)?;
            let result = query_catalog(&catalog, &sql).context("query failed")?;
            print_query_result(&result.columns, &result.rows, format)?;
        }
        Commands::Sparql { workspace, query, format } => {
            let catalog = build_catalog(&workspace)?;
            let result = sparql_catalog(&catalog, &query).context("sparql failed")?;
            match format {
                OutputFormat::Json => println!("{}", sparql_to_json(&result)?),
                _ => print_query_result(&result.columns, &result.rows, format)?,
            }
        }
        Commands::Validate { workspace } => {
            let catalog = build_catalog(&workspace)?;
            let data = catalog.data();
            let mut error_count = 0usize;
            let mut warning_count = 0usize;

            for diag in &data.diagnostics {
                match diag.severity {
                    ontoindex_core::DiagnosticSeverity::Error => {
                        error_count += 1;
                        eprintln!(
                            "ERROR [{}] {}:{}:{}: {}",
                            diag.code.as_str(),
                            diag.file.display(),
                            diag.range.line.unwrap_or(0),
                            diag.range.column.unwrap_or(0),
                            diag.message
                        );
                    }
                    ontoindex_core::DiagnosticSeverity::Warning => {
                        warning_count += 1;
                        eprintln!(
                            "WARN  [{}] {}:{}:{}: {}",
                            diag.code.as_str(),
                            diag.file.display(),
                            diag.range.line.unwrap_or(0),
                            diag.range.column.unwrap_or(0),
                            diag.message
                        );
                    }
                    ontoindex_core::DiagnosticSeverity::Info => {
                        eprintln!(
                            "INFO  [{}] {}: {}",
                            diag.code.as_str(),
                            diag.file.display(),
                            diag.message
                        );
                    }
                }
            }

            if error_count > 0 {
                bail!("validation failed with {error_count} error(s), {warning_count} warning(s)");
            }
            println!(
                "OK: indexed {} ontology file(s), {} warning(s)",
                data.stats().ontology_count,
                warning_count
            );
        }
        Commands::Inspect { workspace, format } => {
            let catalog = build_catalog(&workspace)?;
            print_stats(&catalog.data().stats(), format)?;
        }
        Commands::Patch { document, patch_file, preview } => {
            let patches: Vec<ontoindex_owl::PatchOp> =
                serde_json::from_slice(&std::fs::read(&patch_file)?)
                    .context("failed to parse patch JSON")?;
            let catalog = IndexBuilder::new()
                .workspace(document.parent().unwrap_or(std::path::Path::new(".")))
                .build()
                .ok();
            let namespaces = catalog
                .as_ref()
                .and_then(|c| {
                    c.data().documents.iter().find(|d| {
                        d.path.canonicalize().ok().as_ref() == document.canonicalize().ok().as_ref()
                    })
                })
                .map(|d| d.namespaces.clone())
                .unwrap_or_default();
            let result = ontoindex_owl::apply_patches(&document, &patches, preview, &namespaces)
                .context("patch failed")?;
            println!("{}", serde_json::to_string_pretty(&result)?);
            if !preview && result.applied {
                println!("applied");
            }
        }
        Commands::Classify { workspace, profile, auto_profile, format } => {
            let result = run_classify(&workspace, &profile, auto_profile)?;
            match format {
                OutputFormat::Json => println!("{}", serde_json::to_string_pretty(&result)?),
                OutputFormat::Text | OutputFormat::Csv => {
                    println!("profile: {}", result.profile_used);
                    println!("consistent: {}", result.consistent);
                    println!("unsatisfiable: {}", result.unsatisfiable.len());
                    println!("inferred_edges: {}", result.inferred.edges.len());
                    println!("new_inferences: {}", result.new_inferences.len());
                    println!("duration_ms: {}", result.duration_ms);
                    for iri in &result.unsatisfiable {
                        println!("UNSAT {iri}");
                    }
                    for edge in &result.new_inferences {
                        println!("INFERRED {} SubClassOf {}", edge.child, edge.parent);
                    }
                }
            }
            if !result.consistent {
                bail!(
                    "classification found {} unsatisfiable class(es)",
                    result.unsatisfiable.len()
                );
            }
        }
        Commands::Explain { workspace, class, profile, format } => {
            let result = run_explain(&workspace, &class, &profile)?;
            match format {
                OutputFormat::Json => println!("{}", serde_json::to_string_pretty(&result)?),
                OutputFormat::Text | OutputFormat::Csv => {
                    println!("class: {}", result.class_iri);
                    println!("{}", result.text);
                }
            }
        }
        Commands::Robot { command } => {
            use ontoindex_robot::{robot_merge, robot_report, robot_validate};
            let output = match command {
                RobotCommands::Validate { path, robot_path } => {
                    robot_validate(robot_path.as_deref(), &path)?
                }
                RobotCommands::Merge { inputs, output, robot_path } => {
                    let input_strs: Vec<String> =
                        inputs.iter().map(|p| p.display().to_string()).collect();
                    robot_merge(robot_path.as_deref(), &input_strs, &output)?
                }
                RobotCommands::Report { path, report, robot_path } => {
                    robot_report(robot_path.as_deref(), &path, &report)?
                }
            };
            if !output.stdout.is_empty() {
                print!("{}", output.stdout);
            }
            if !output.stderr.is_empty() {
                eprint!("{}", output.stderr);
            }
            if output.exit_code != 0 {
                std::process::exit(output.exit_code);
            }
        }
        Commands::Refactor { command } => match command {
            RefactorCommands::Usages { workspace, iri, format } => {
                let catalog = build_catalog(&workspace)?;
                let usages = find_usages(&catalog, &iri);
                match format {
                    OutputFormat::Json => {
                        println!("{}", serde_json::to_string_pretty(&usages)?);
                    }
                    _ => {
                        for u in usages {
                            println!(
                                "{}:{}:{} {:?} {}",
                                u.file.display(),
                                u.line.unwrap_or(0),
                                u.column.unwrap_or(0),
                                u.kind,
                                u.context
                            );
                        }
                    }
                }
            }
            RefactorCommands::Rename { workspace, from, to, preview, format } => {
                let catalog = build_catalog(&workspace)?;
                let plan = preview_rename_iri(&catalog, &from, &to, &HashMap::new())?;
                run_refactor_plan(&plan, preview, format, &workspace)?;
            }
            RefactorCommands::MigrateNamespace { workspace, from, to, preview, format } => {
                let catalog = build_catalog(&workspace)?;
                let plan = preview_migrate_namespace(&catalog, &from, &to, &HashMap::new())?;
                run_refactor_plan(&plan, preview, format, &workspace)?;
            }
            RefactorCommands::Move { workspace, iri, to, preview, format } => {
                let catalog = build_catalog(&workspace)?;
                let plan = preview_move_entity(&catalog, &iri, &to, &HashMap::new())?;
                run_refactor_plan(&plan, preview, format, &workspace)?;
            }
            RefactorCommands::Extract { workspace, entities, out, leave_stub, preview, format } => {
                let catalog = build_catalog(&workspace)?;
                let plan =
                    preview_extract_module(&catalog, &entities, &out, leave_stub, &HashMap::new())?;
                run_refactor_plan(&plan, preview, format, &workspace)?;
            }
        },
    }
    Ok(())
}

fn run_refactor_plan(
    plan: &RefactorPlan,
    preview: bool,
    format: OutputFormat,
    workspace: &Path,
) -> Result<()> {
    match format {
        OutputFormat::Json => println!("{}", serde_json::to_string_pretty(plan)?),
        _ => {
            for change in &plan.changes {
                println!("{}: {} byte(s) changed", change.path.display(), change.hunks.len());
            }
            for w in &plan.warnings {
                eprintln!("WARN: {w}");
            }
        }
    }
    let files_written = apply_refactor_plan_checked(plan, preview, Some(workspace))?;
    if !preview {
        println!("applied {files_written} file(s)");
    }
    Ok(())
}

fn build_catalog(workspace: &PathBuf) -> Result<OntologyCatalog> {
    IndexBuilder::new()
        .workspace(workspace)
        .build()
        .with_context(|| format!("failed to index workspace {}", workspace.display()))
}

fn load_reasoner_input(workspace: &PathBuf) -> Result<ontoindex_reasoner::ReasonerInput> {
    let catalog = build_catalog(workspace)?;
    WorkspaceInputLoader::new(workspace)
        .load(catalog.class_hierarchy())
        .map_err(|e| anyhow::anyhow!(e))
}

fn run_classify(
    workspace: &PathBuf,
    profile: &str,
    auto_profile: bool,
) -> Result<ontoindex_reasoner::ClassificationResult> {
    let profile_id = ReasonerId::parse(profile).map_err(|e| anyhow::anyhow!(e))?;
    let input = load_reasoner_input(workspace)?;
    classify(profile_id, &input, auto_profile).map_err(|e| anyhow::anyhow!(e))
}

fn run_explain(
    workspace: &PathBuf,
    class: &str,
    profile: &str,
) -> Result<ontoindex_reasoner::ExplanationResult> {
    let profile_id = ReasonerId::parse(profile).map_err(|e| anyhow::anyhow!(e))?;
    let input = load_reasoner_input(workspace)?;
    explain(profile_id, &input, &ExplanationRequest { class_iri: class.to_string() })
        .map_err(|e| anyhow::anyhow!(e))
}

fn print_stats(stats: &CatalogStats, format: OutputFormat) -> Result<()> {
    match format {
        OutputFormat::Json => println!("{}", serde_json::to_string_pretty(stats)?),
        OutputFormat::Csv | OutputFormat::Text => {
            println!("ontologies:            {}", stats.ontology_count);
            println!("classes:               {}", stats.class_count);
            println!("object_properties:     {}", stats.object_property_count);
            println!("data_properties:       {}", stats.data_property_count);
            println!("annotation_properties: {}", stats.annotation_property_count);
            println!("individuals:           {}", stats.individual_count);
            println!("axioms:                {}", stats.axiom_count);
            println!("annotations:           {}", stats.annotation_count);
            println!("triples:               {}", stats.triple_count);
            println!("parse_errors:          {}", stats.error_count);
            println!("diagnostic_errors:     {}", stats.diagnostic_error_count);
            println!("diagnostic_warnings:   {}", stats.diagnostic_warning_count);
        }
    }
    Ok(())
}

fn print_query_result(
    columns: &[String],
    rows: &[std::collections::BTreeMap<String, String>],
    format: OutputFormat,
) -> Result<()> {
    let result = ontoindex_query::sql::QueryResult {
        columns: columns.to_vec(),
        rows: rows.to_vec(),
        truncated: false,
    };
    match format {
        OutputFormat::Json => println!("{}", sql_to_json(&result)?),
        OutputFormat::Csv => print!("{}", sql_to_csv(&result)?),
        OutputFormat::Text => {
            if columns.is_empty() {
                println!("(no columns)");
                return Ok(());
            }
            println!("{}", columns.join("\t"));
            for row in rows {
                let line: Vec<String> =
                    columns.iter().map(|c| row.get(c).cloned().unwrap_or_default()).collect();
                println!("{}", line.join("\t"));
            }
        }
    }
    Ok(())
}