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
# frozen_string_literal: true
# High-level Ruby interface to an AgentDB database.
#
# Example:
# db = AgentDB::Database.new("agent.agentdb")
#
# # SQL
# db.execute("CREATE TABLE IF NOT EXISTS notes (id TEXT, body TEXT)")
# db.execute("INSERT INTO notes VALUES ('n1', 'hello world')")
# rows = db.query("SELECT * FROM notes") # => [{"id"=>"n1","body"=>"hello world"}]
#
# # Vectors
# col = db.collection("memories", 1536)
# col.upsert("mem1", embedding, { topic: "ruby" })
# results = col.search(query_embedding, top_k: 5)
#
# db.close
#
# Use a block form to ensure the handle is always closed:
# AgentDB::Database.open("agent.agentdb") do |db|
# db.execute("SELECT 1")
# end
# Open (or create) an AgentDB database at +path+.
#
# Pass +":memory:"+ for a transient in-process database.
#
# @param path [String] file system path or ":memory:"
# @raise [AgentDB::DatabaseError] if the library reports an error
@handle = FFIBindings.agentdb_open(path.to_s)
if @handle.null?
msg = FFIBindings.last_error ||
raise AgentDB::DatabaseError,
end
@closed = false
end
# Open a database, yield to the block, and close it even if the block
# raises.
#
# @param path [String] file path or ":memory:"
# @yieldparam db [AgentDB::Database]
# @return the block's return value
db = new(path)
return db unless block_given?
begin
block.call(db)
ensure
db.close
end
end
# Close the database and release the native handle.
#
# Calling close more than once is safe.
return if @closed
FFIBindings.agentdb_close(@handle)
@closed = true
end
# @return [Boolean] true if the database handle has been closed
@closed
end
# Execute a raw SQL statement.
#
# @param sql [String] any DDL or DML statement
# @return [Integer] number of rows affected
# @raise [AgentDB::FFIError] on SQL error
ensure_open!
rc = FFIBindings.agentdb_execute(@handle, sql.to_s)
if rc == -1
msg = FFIBindings.last_error ||
raise AgentDB::FFIError,
end
rc
end
# Query rows and return them as an array of hashes.
#
# @param sql [String] SELECT statement
# @return [Array<Hash>] rows as Ruby hashes with string keys
# @raise [AgentDB::FFIError] on SQL error
ensure_open!
ptr = FFIBindings.agentdb_query_json(@handle, sql.to_s)
json_string = read_json_ptr!(ptr, )
JSON.parse(json_string)
end
# Query rows with positional parameters.
#
# Parameters are supplied as a Ruby array and serialised to a JSON array
# before being passed to the C layer, which maps them to SQL +?+ placeholders.
#
# @param sql [String] parameterised SELECT, e.g. "SELECT * FROM t WHERE x = ?"
# @param params [Array] parameter values (strings, numbers, booleans, nil)
# @return [Array<Hash>]
# @raise [AgentDB::FFIError] on SQL error
ensure_open!
params_json = params.to_json
ptr = FFIBindings.agentdb_query_json_params(@handle, sql.to_s, params_json)
json_string = read_json_ptr!(ptr, )
JSON.parse(json_string)
end
# Return a Collection object for vector operations.
#
# The collection is created inside the database on first upsert if it does
# not already exist.
#
# @param name [String] collection name
# @param dim [Integer] vector dimensionality
# @return [AgentDB::Collection]
ensure_open!
Collection.new(@handle, name, dim)
end
# Return database statistics as a Hash.
#
# Keys: collections, vectors, nodes, edges, conversations, messages,
# workflows, workflow_steps, traces, tools, tool_calls,
# audit_entries, prompt_templates
#
# @return [Hash]
# @raise [AgentDB::FFIError] on error
ensure_open!
ptr = FFIBindings.agentdb_stats(@handle)
json_string = read_json_ptr!(ptr, )
JSON.parse(json_string)
end
# ── Memory graph ──────────────────────────────────────────────────────
# Add or update a node in the memory graph.
#
# @param id [String] unique node identifier
# @param kind [String] node type label (e.g. "session", "concept")
# @param data [Hash, nil] arbitrary JSON-serialisable metadata
# @raise [AgentDB::FFIError] on error
ensure_open!
data_json = data ? data.to_json : nil
rc = FFIBindings.agentdb_graph_add_node(@handle, id.to_s, kind.to_s, data_json)
check_rc!(rc, )
end
# Add or update a directed weighted edge between two nodes.
#
# @param src [String] source node ID
# @param dst [String] destination node ID
# @param relation [String] edge type / label
# @param weight [Float] edge weight (0.0–1.0 typical)
# @raise [AgentDB::FFIError] on error
ensure_open!
rc = FFIBindings.agentdb_graph_add_edge(
@handle, src.to_s, dst.to_s, relation.to_s, weight.to_f
)
check_rc!(rc, )
end
# Traverse from a node and return neighbouring nodes.
#
# @param node_id [String] starting node ID
# @param max_depth [Integer] maximum hops (default: 2)
# @param min_weight [Float] minimum edge weight to follow (default: 0.0)
# @param relation [String, nil] filter to a specific edge relation
# @return [Array<Hash>] nodes with id, kind, depth, weight, data keys
# @raise [AgentDB::FFIError] on error
ensure_open!
ptr = FFIBindings.agentdb_graph_neighbors(
@handle, node_id.to_s, max_depth.to_i, min_weight.to_f, relation&.to_s
)
json_string = read_json_ptr!(ptr, )
JSON.parse(json_string)
end
# Fetch a single graph node by ID.
#
# @param id [String] node identifier
# @return [Hash] node with id, kind, data, created_at, updated_at
# @raise [AgentDB::FFIError] on error
ensure_open!
ptr = FFIBindings.agentdb_graph_get_node(@handle, id.to_s)
json_string = read_json_ptr!(ptr, )
JSON.parse(json_string)
end
# Delete a graph node and all its connected edges (CASCADE).
#
# @param id [String] node identifier
# @raise [AgentDB::FFIError] on error
ensure_open!
rc = FFIBindings.agentdb_graph_delete_node(@handle, id.to_s)
check_rc!(rc, )
end
# Delete a specific directed edge.
#
# @param src [String] source node ID
# @param dst [String] destination node ID
# @param relation [String] edge relation / label
# @raise [AgentDB::FFIError] on error
ensure_open!
rc = FFIBindings.agentdb_graph_delete_edge(
@handle, src.to_s, dst.to_s, relation.to_s
)
check_rc!(rc, )
end
# ── Hybrid queries ────────────────────────────────────────────────────
# Run a hybrid graph-traversal + vector similarity query.
#
# @param anchor_node [String] graph traversal start node ID
# @param embedding [Array<Float>] query vector
# @param dim [Integer] embedding dimensions
# @param collection [String] vector collection name
# @param graph_depth [Integer] max traversal hops (default: 2)
# @param top_k [Integer] results to return (default: 10)
# @param alpha [Float] blending factor 0.0=graph, 1.0=vector
# @param filter [Hash, nil] optional metadata filter
# @return [Array<Hash>] id, rank_score, vector_score, graph_weight per result
# @raise [AgentDB::FFIError] on error
ensure_open!
buf, size = FFIBindings.pack_floats(embedding)
filter_json = filter ? filter.to_json : nil
ptr = FFIBindings.agentdb_hybrid_query(
@handle,
anchor_node.to_s,
buf, size,
collection.to_s,
graph_depth.to_i,
top_k.to_i,
alpha.to_f,
filter_json
)
json_string = read_json_ptr!(ptr, )
JSON.parse(json_string)
end
# ── Conversations ─────────────────────────────────────────────────────
# Create a new conversation record.
#
# @param id [String] unique conversation identifier
# @param title [String, nil] optional display title
# @param metadata [Hash, nil] optional JSON metadata
# @raise [AgentDB::FFIError] on error
ensure_open!
meta_json = metadata ? metadata.to_json : nil
rc = FFIBindings.agentdb_conversation_create(
@handle, id.to_s, title&.to_s, meta_json
)
check_rc!(rc, )
end
# Append a message to an existing conversation.
#
# @param conversation_id [String] target conversation
# @param role [String] "user", "assistant", "system", etc.
# @param content [String] message body
# @param metadata [Hash, nil] optional JSON metadata
# @return [String] the new message ID
# @raise [AgentDB::FFIError] on error
ensure_open!
meta_json = metadata ? metadata.to_json : nil
ptr = FFIBindings.agentdb_conversation_add_message(
@handle, conversation_id.to_s, role.to_s, content.to_s, meta_json
)
read_string_ptr!(ptr, )
end
# Retrieve messages for a conversation.
#
# @param conversation_id [String] target conversation
# @param limit [Integer, nil] max messages (nil = all)
# @return [Array<Hash>]
# @raise [AgentDB::FFIError] on error
ensure_open!
ptr = FFIBindings.agentdb_conversation_get_messages(
@handle, conversation_id.to_s, (limit || 0).to_i
)
json_string = read_json_ptr!(ptr, )
JSON.parse(json_string)
end
# List all conversations.
#
# @return [Array<Hash>]
# @raise [AgentDB::FFIError] on error
ensure_open!
ptr = FFIBindings.agentdb_conversation_list(@handle)
json_string = read_json_ptr!(ptr, )
JSON.parse(json_string)
end
# Delete a conversation and all its messages.
#
# @param id [String] conversation identifier
# @raise [AgentDB::FFIError] on error
ensure_open!
rc = FFIBindings.agentdb_conversation_delete(@handle, id.to_s)
check_rc!(rc, )
end
# ── Workflows ─────────────────────────────────────────────────────────
# Create a new workflow.
#
# @param id [String] unique workflow identifier
# @param name [String] human-readable name
# @param input [Hash, nil] optional JSON input
# @param metadata [Hash, nil] optional JSON metadata
# @raise [AgentDB::FFIError] on error
ensure_open!
rc = FFIBindings.agentdb_workflow_create(
@handle,
id.to_s, name.to_s,
input ? input.to_json : nil,
metadata ? metadata.to_json : nil
)
check_rc!(rc, )
end
# Add a step to an existing workflow.
#
# @param workflow_id [String] workflow identifier
# @param name [String] step name
# @param input [Hash, nil] optional JSON input
# @return [String] new step ID
# @raise [AgentDB::FFIError] on error
ensure_open!
ptr = FFIBindings.agentdb_workflow_add_step(
@handle, workflow_id.to_s, name.to_s, input ? input.to_json : nil
)
read_string_ptr!(ptr, )
end
# Update a workflow step.
#
# @param step_id [String] step identifier
# @param status [String] "running", "completed", or "failed"
# @param output [Hash, nil] optional JSON output
# @param error [String, nil] optional error message
# @raise [AgentDB::FFIError] on error
ensure_open!
rc = FFIBindings.agentdb_workflow_update_step(
@handle,
step_id.to_s, status.to_s,
output ? output.to_json : nil,
error&.to_s
)
check_rc!(rc, )
end
# Mark a workflow as completed.
#
# @param id [String] workflow identifier
# @param output [Hash, nil] optional JSON result
# @raise [AgentDB::FFIError] on error
ensure_open!
rc = FFIBindings.agentdb_workflow_complete(
@handle, id.to_s, output ? output.to_json : nil
)
check_rc!(rc, )
end
# Mark a workflow as failed.
#
# @param id [String] workflow identifier
# @param error [String, nil] optional error description
# @raise [AgentDB::FFIError] on error
ensure_open!
rc = FFIBindings.agentdb_workflow_fail(@handle, id.to_s, error&.to_s)
check_rc!(rc, )
end
# Retrieve a workflow with all its steps.
#
# @param id [String] workflow identifier
# @return [Hash]
# @raise [AgentDB::FFIError] on error
ensure_open!
ptr = FFIBindings.agentdb_workflow_get(@handle, id.to_s)
json_string = read_json_ptr!(ptr, )
JSON.parse(json_string)
end
# List workflows, optionally filtered by status.
#
# @param status [String, nil] "pending", "running", "completed", "failed", or nil for all
# @return [Array<Hash>]
# @raise [AgentDB::FFIError] on error
ensure_open!
ptr = FFIBindings.agentdb_workflow_list(@handle, status&.to_s)
json_string = read_json_ptr!(ptr, )
JSON.parse(json_string)
end
# ── Traces ────────────────────────────────────────────────────────────
# Record a reasoning trace entry.
#
# @param trace_type [String] type label (e.g. "thought", "action")
# @param content [String] trace body
# @param session_id [String, nil] optional session context
# @param parent_id [String, nil] optional parent trace ID for nesting
# @param metadata [Hash, nil] optional JSON metadata
# @return [String] new trace ID
# @raise [AgentDB::FFIError] on error
ensure_open!
ptr = FFIBindings.agentdb_trace_add(
@handle,
session_id&.to_s, parent_id&.to_s,
trace_type.to_s, content.to_s,
metadata ? metadata.to_json : nil
)
read_string_ptr!(ptr, )
end
# Retrieve all traces for a session.
#
# @param session_id [String] session identifier
# @return [Array<Hash>]
# @raise [AgentDB::FFIError] on error
ensure_open!
ptr = FFIBindings.agentdb_trace_get_by_session(@handle, session_id.to_s)
json_string = read_json_ptr!(ptr, )
JSON.parse(json_string)
end
# Retrieve a trace subtree rooted at +root_id+.
#
# @param root_id [String] root trace ID
# @return [Array<Hash>]
# @raise [AgentDB::FFIError] on error
ensure_open!
ptr = FFIBindings.agentdb_trace_get_tree(@handle, root_id.to_s)
json_string = read_json_ptr!(ptr, )
JSON.parse(json_string)
end
private
raise AgentDB::DatabaseError, if @closed
end
return if rc >= 0
msg = FFIBindings.last_error ||
raise AgentDB::FFIError,
end
# Read a heap-allocated JSON string, free it, and raise if NULL.
if ptr.nil? || ptr.null?
msg = FFIBindings.last_error ||
raise AgentDB::FFIError,
end
FFIBindings.read_and_free(ptr)
end
# Read a heap-allocated plain string (not necessarily JSON), free it,
# and raise if NULL.
if ptr.nil? || ptr.null?
msg = FFIBindings.last_error ||
raise AgentDB::FFIError,
end
FFIBindings.read_and_free(ptr)
end
end
end