datacules-agentdb 0.5.3

Single-file embedded database for AI agents. SQL + Vector Search + Full-Text Search + Hybrid Queries + Memory Graphs.
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
//! # agentdb CLI
//!
//! Inspect, query, and manage AgentDB database files from the command line.
//!
//! ## Commands
//!
//! ```text
//! agentdb stats       <path>                  — print database statistics
//! agentdb collections <path>                  — list all vector collections
//! agentdb sql         <path> <query>          — run a SQL query, print JSON
//! agentdb search      <path> <col> <vec...>   — ANN vector search
//! agentdb reindex     <path>                  — rebuild all dirty HNSW indexes
//! agentdb inspect     <path>                  — full database summary
//! agentdb shell       <path>                  — interactive SQL/dot-command REPL
//! ```
//!
//! ## Examples
//!
//! ```bash
//! # Install from crates.io
//! cargo install agentdb
//!
//! # Stats
//! agentdb stats agent.agentdb
//!
//! # Run SQL
//! agentdb sql agent.agentdb "SELECT * FROM sessions LIMIT 5"
//!
//! # Full inspection
//! agentdb inspect agent.agentdb
//!
//! # Interactive shell
//! agentdb shell agent.agentdb
//! agentdb -i agent.agentdb
//! ```

use agentdb::AgentDB;
use clap::{Parser, Subcommand};

// ── CLI definition ────────────────────────────────────────────────────

#[derive(Parser)]
#[command(
    name = "agentdb",
    version = env!("CARGO_PKG_VERSION"),
    about = "Inspect and manage AgentDB database files",
    long_about = None,
)]
struct Cli {
    /// Open the database at PATH in an interactive shell (alias for `agentdb shell <PATH>`).
    #[arg(short = 'i', long = "interactive", value_name = "PATH")]
    interactive: Option<String>,

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

#[derive(Subcommand)]
enum Commands {
    /// Print database-wide statistics.
    Stats {
        /// Path to the .agentdb file (or :memory: for a blank in-memory DB).
        path: String,
    },

    /// List all vector collections with their dimension and vector count.
    Collections { path: String },

    /// Run a SQL query and print results as pretty-printed JSON.
    Sql {
        path: String,
        /// SQL query to execute.
        query: String,
    },

    /// Approximate nearest-neighbor search in a vector collection.
    Search {
        path: String,
        /// Collection name to search.
        collection: String,
        /// Query vector values (space-separated floats).
        #[arg(num_args = 1.., value_name = "f32")]
        vector: Vec<f32>,
        /// Number of results to return.
        #[arg(short, long, default_value_t = 5)]
        top_k: usize,
    },

    /// Rebuild all dirty HNSW indexes in the database.
    Reindex { path: String },

    /// Print a full summary: stats + collections + recent nodes.
    Inspect { path: String },

    /// Migrate a database to the current schema version.
    ///
    /// Re-runs the schema bootstrap to add any missing tables or indexes
    /// introduced in newer versions of AgentDB. Existing data is preserved.
    Migrate { path: String },

    /// Open an interactive SQL / dot-command REPL.
    ///
    /// SQL statements are terminated by a semicolon and may span multiple lines.
    /// Dot-commands are single-line helpers:
    ///
    ///   .help          — show this help text
    ///   .stats         — database statistics
    ///   .collections   — list all vector collections
    ///   .inspect       — full database summary
    ///   .quit / .exit  — leave the shell
    Shell {
        /// Path to the .agentdb file (or :memory: for a blank in-memory DB).
        path: String,
    },
}

// ── Entry point ───────────────────────────────────────────────────────

fn main() {
    let cli = Cli::parse();

    if let Err(e) = run(cli) {
        eprintln!("error: {e}");
        std::process::exit(1);
    }
}

fn run(cli: Cli) -> agentdb::Result<()> {
    // --interactive / -i flag takes precedence when no subcommand is given.
    if let Some(path) = cli.interactive {
        return cmd_shell(&path);
    }

    match cli.command {
        Some(Commands::Stats { path }) => cmd_stats(&path),
        Some(Commands::Collections { path }) => cmd_collections(&path),
        Some(Commands::Sql { path, query }) => cmd_sql(&path, &query),
        Some(Commands::Search {
            path,
            collection,
            vector,
            top_k,
        }) => cmd_search(&path, &collection, &vector, top_k),
        Some(Commands::Reindex { path }) => cmd_reindex(&path),
        Some(Commands::Inspect { path }) => cmd_inspect(&path),
        Some(Commands::Migrate { path }) => cmd_migrate(&path),
        Some(Commands::Shell { path }) => cmd_shell(&path),
        None => {
            // Neither a subcommand nor -i was supplied — print help.
            use std::io::Write as _;
            let _ = writeln!(
                std::io::stderr(),
                "No command specified. Run `agentdb --help` for usage."
            );
            std::process::exit(2);
        }
    }
}

// ── Command implementations ───────────────────────────────────────────

fn cmd_stats(path: &str) -> agentdb::Result<()> {
    let db = AgentDB::open(path)?;
    let s = db.stats()?;
    println!("path:           {path}");
    println!("collections:    {}", s.collections);
    println!("vectors:        {}", s.vectors);
    println!("nodes:          {}", s.nodes);
    println!("edges:          {}", s.edges);
    println!("conversations:  {}", s.conversations);
    println!("messages:       {}", s.messages);
    println!("workflows:      {}", s.workflows);
    println!("workflow_steps: {}", s.workflow_steps);
    println!("traces:         {}", s.traces);
    Ok(())
}

fn cmd_collections(path: &str) -> agentdb::Result<()> {
    let db = AgentDB::open(path)?;
    let cols = db.vectors().list_collections()?;
    if cols.is_empty() {
        println!("No collections found.");
        return Ok(());
    }
    println!("{:<30} {:>6} {:>10}", "name", "dim", "vectors");
    println!("{}", "-".repeat(50));
    for (name, dim, count) in &cols {
        println!("{:<30} {:>6} {:>10}", name, dim, count);
    }
    Ok(())
}

fn cmd_sql(path: &str, query: &str) -> agentdb::Result<()> {
    let db = AgentDB::open(path)?;
    let rows = db.query_json(query)?;
    println!(
        "{}",
        serde_json::to_string_pretty(&rows).unwrap_or_default()
    );
    Ok(())
}

fn cmd_search(path: &str, collection: &str, vector: &[f32], top_k: usize) -> agentdb::Result<()> {
    use agentdb::{DistanceMetric, SearchOptions};

    let db = AgentDB::open(path)?;
    let dim = vector.len();
    let col = db.vectors().collection(collection, dim)?;
    let results = col.search(
        vector,
        SearchOptions {
            top_k,
            metric: DistanceMetric::Cosine,
            filter: None,
        },
    )?;

    if results.is_empty() {
        println!("No results.");
        return Ok(());
    }
    println!("{:<30} {:>8}  metadata", "id", "score");
    println!("{}", "-".repeat(60));
    for r in &results {
        let meta = r
            .metadata
            .as_ref()
            .map(|m| m.to_string())
            .unwrap_or_default();
        println!("{:<30} {:>8.4}  {}", r.id, r.score, meta);
    }
    Ok(())
}

fn cmd_reindex(path: &str) -> agentdb::Result<()> {
    let db = AgentDB::open(path)?;
    let cols = db.vectors().list_collections()?;
    let mut rebuilt = 0usize;
    for (name, dim, _) in &cols {
        let col = db.vectors().collection(name, *dim)?;
        col.reindex()?;
        rebuilt += 1;
        println!("reindexed: {name}");
    }
    println!("done — {rebuilt} collection(s) reindexed.");
    Ok(())
}

fn cmd_inspect(path: &str) -> agentdb::Result<()> {
    let db = AgentDB::open(path)?;

    println!("=== AgentDB Inspect ===");
    println!("path: {path}");
    println!();

    let s = db.stats()?;
    println!("Statistics");
    println!("  collections    : {}", s.collections);
    println!("  vectors        : {}", s.vectors);
    println!("  nodes          : {}", s.nodes);
    println!("  edges          : {}", s.edges);
    println!("  conversations  : {}", s.conversations);
    println!("  messages       : {}", s.messages);
    println!("  workflows      : {}", s.workflows);
    println!("  workflow_steps : {}", s.workflow_steps);
    println!("  traces         : {}", s.traces);
    println!();

    let cols = db.vectors().list_collections()?;
    if !cols.is_empty() {
        println!("Collections");
        println!("  {:<28} {:>6} {:>10}", "name", "dim", "vectors");
        println!("  {}", "-".repeat(48));
        for (name, dim, count) in &cols {
            println!("  {:<28} {:>6} {:>10}", name, dim, count);
        }
        println!();
    }

    let rows =
        db.query_json("SELECT id, kind FROM _adb_nodes ORDER BY created_at DESC LIMIT 10")?;
    if !rows.is_empty() {
        println!("Recent nodes (up to 10)");
        for row in &rows {
            println!(
                "  {}{}",
                row.get("id").and_then(|v| v.as_str()).unwrap_or("-"),
                row.get("kind").and_then(|v| v.as_str()).unwrap_or("-"),
            );
        }
    }

    Ok(())
}

fn cmd_migrate(path: &str) -> agentdb::Result<()> {
    use rusqlite::Connection;

    println!("Migrating: {path}");

    let conn = Connection::open(path).map_err(agentdb::AgentDbError::Sqlite)?;

    let old_version: String = conn
        .query_row(
            "SELECT COALESCE(
                (SELECT value FROM _adb_meta WHERE key = 'schema_version'),
                '0'
            )",
            [],
            |r| r.get(0),
        )
        .unwrap_or_else(|_| "0".to_string());

    println!("  current schema version: {old_version}");

    agentdb::schema::migrate(&conn)?;

    println!(
        "  migrated to schema version: {}",
        agentdb::schema::SCHEMA_VERSION
    );
    println!("done.");
    Ok(())
}

// ── Interactive shell ─────────────────────────────────────────────────

/// Run an interactive REPL for the database at `path`.
///
/// Input model
/// -----------
/// * SQL statements are accumulated across lines until a semicolon is seen,
///   then executed and the JSON result printed.
/// * Dot-commands (`.help`, `.stats`, `.collections`, `.inspect`,
///   `.quit` / `.exit`) are executed immediately on a single line.
/// * An empty line is ignored.
/// * Ctrl-D (EOF from `read_line` returning `Ok(0)`) exits cleanly.
/// * An `Interrupted` IO error (Ctrl-C on Unix) discards the current buffer
///   and redisplays the prompt so the user can start over.
fn cmd_shell(path: &str) -> agentdb::Result<()> {
    use std::io::{self, BufRead, Write};

    let db = AgentDB::open(path)?;

    println!("AgentDB shell v{}", env!("CARGO_PKG_VERSION"));
    println!("Connected to: {path}");
    println!("Type .help for help, .quit to exit.");
    println!();

    let stdin = io::stdin();
    let stdout = io::stdout();

    // SQL buffer — accumulates lines until a `;` is encountered.
    let mut sql_buf = String::new();

    loop {
        // Choose the prompt: continuation lines use `   ...> ` so the user
        // can see they are still inside a multi-line statement.
        let prompt = if sql_buf.trim().is_empty() {
            "agentdb> "
        } else {
            "      -> "
        };

        // Print the prompt without a newline and flush immediately.
        {
            let mut out = stdout.lock();
            let _ = write!(out, "{prompt}");
            let _ = out.flush();
        }

        let mut line = String::new();
        match stdin.lock().read_line(&mut line) {
            // EOF (Ctrl-D): exit cleanly.
            Ok(0) => {
                println!();
                println!("Bye.");
                break;
            }
            Ok(_) => {}
            Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {
                // Ctrl-C on Unix: discard current buffer and continue.
                if !sql_buf.is_empty() {
                    println!("  (input cleared)");
                    sql_buf.clear();
                } else {
                    println!();
                }
                continue;
            }
            Err(e) => {
                eprintln!("read error: {e}");
                break;
            }
        }

        let trimmed = line.trim();

        // Skip blank lines.
        if trimmed.is_empty() {
            continue;
        }

        // ── Dot-commands ──────────────────────────────────────────────
        if trimmed.starts_with('.') {
            // Dot-commands are only valid when no SQL buffer is in progress.
            if !sql_buf.trim().is_empty() {
                eprintln!(
                    "error: complete the current statement first (end with `;`), \
                     or press Ctrl-C to discard it."
                );
                continue;
            }

            match trimmed {
                ".quit" | ".exit" => {
                    println!("Bye.");
                    break;
                }
                ".help" => shell_help(),
                ".stats" => {
                    if let Err(e) = cmd_stats(path) {
                        eprintln!("error: {e}");
                    }
                }
                ".collections" => {
                    if let Err(e) = cmd_collections(path) {
                        eprintln!("error: {e}");
                    }
                }
                ".inspect" => {
                    if let Err(e) = cmd_inspect(path) {
                        eprintln!("error: {e}");
                    }
                }
                other => {
                    eprintln!("Unknown dot-command: {other}");
                    eprintln!("Type .help for a list of commands.");
                }
            }
            continue;
        }

        // ── SQL accumulation ──────────────────────────────────────────
        sql_buf.push_str(&line);

        // Execute when the accumulated buffer ends with a semicolon
        // (ignoring trailing whitespace after the semicolon).
        if sql_buf.trim_end().ends_with(';') {
            let query = sql_buf.trim().to_string();
            sql_buf.clear();

            // Route non-SELECT statements to execute() so rows-affected is shown.
            let upper = query.trim_start().to_ascii_uppercase();
            let is_select = upper.starts_with("SELECT")
                || upper.starts_with("WITH")
                || upper.starts_with("PRAGMA")
                || upper.starts_with("EXPLAIN");
            if is_select {
                match db.query_json(&query) {
                    Ok(rows) => {
                        println!(
                            "{}",
                            serde_json::to_string_pretty(&rows).unwrap_or_default()
                        );
                        println!(
                            "({} row{})",
                            rows.len(),
                            if rows.len() == 1 { "" } else { "s" }
                        );
                    }
                    Err(e) => eprintln!("error: {e}"),
                }
            } else {
                match db.execute(&query) {
                    Ok(n) => println!("({n} row{} affected)", if n == 1 { "" } else { "s" }),
                    Err(e) => eprintln!("error: {e}"),
                }
            }
        }
    }

    Ok(())
}

/// Print the shell help text.
fn shell_help() {
    println!("AgentDB interactive shell");
    println!();
    println!("SQL queries");
    println!("  Enter any SQL statement.  Statements may span multiple lines.");
    println!("  Terminate with a semicolon (;) to execute.");
    println!();
    println!("Dot-commands");
    println!("  .help          show this help text");
    println!("  .stats         print database statistics");
    println!("  .collections   list vector collections");
    println!("  .inspect       full database summary");
    println!("  .quit          exit the shell");
    println!("  .exit          exit the shell (alias for .quit)");
    println!();
    println!("Keyboard shortcuts");
    println!("  Ctrl-C         discard current input line and start fresh");
    println!("  Ctrl-D         exit the shell (EOF)");
}