geographdb-core 0.5.4

Geometric graph database core - 3D spatial indexing for code analysis
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! Tool schema parsing and subgraph construction for structure decoding.
//!
//! Extracts JSON function schemas from tool-use datasets (e.g. Glaive) and
//! builds small anchor/argument subgraphs inside the geometric graph.

use crate::algorithms::four_d::{GraphNode4D, GraphProperties, TemporalEdge};
use anyhow::{Context, Result};
use glam::Vec3;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap, HashSet};

/// A parsed function-calling tool schema.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolSchema {
    pub name: String,
    #[serde(default)]
    pub description: String,
    #[serde(default)]
    pub parameters: serde_json::Value,
}

impl ToolSchema {
    /// Required parameter names according to the schema.
    pub fn required_params(&self) -> Vec<String> {
        if let Some(arr) = self.parameters.get("required").and_then(|v| v.as_array()) {
            arr.iter()
                .filter_map(|v| v.as_str().map(|s| s.to_string()))
                .collect()
        } else {
            Vec::new()
        }
    }

    /// Parameter name → type/description map.
    pub fn param_properties(&self) -> BTreeMap<String, serde_json::Value> {
        if let Some(obj) = self
            .parameters
            .get("properties")
            .and_then(|v| v.as_object())
        {
            obj.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
        } else {
            BTreeMap::new()
        }
    }
}

/// Extract the first top-level JSON object from a text block.
///
/// Glaive tool schemas are embedded inside a `SYSTEM:` preamble; this function
/// finds the first `{`, tracks brace balance, and returns the matching object
/// string.
pub fn extract_json_object(text: &str) -> Option<String> {
    let start = text.find('{')?;
    let mut depth = 0i32;
    let mut in_string = false;
    let mut escape = false;
    let bytes = text.as_bytes();

    for i in start..bytes.len() {
        let b = bytes[i];
        if in_string {
            if escape {
                escape = false;
                continue;
            }
            if b == b'\\' {
                escape = true;
                continue;
            }
            if b == b'"' {
                in_string = false;
            }
            continue;
        }

        match b {
            b'"' => in_string = true,
            b'{' => depth += 1,
            b'}' => {
                depth -= 1;
                if depth == 0 {
                    return String::from_utf8(bytes[start..=i].to_vec()).ok();
                }
            }
            _ => {}
        }
    }
    None
}

/// Parse tool schemas from a list of `system` text snippets.
pub fn parse_tool_schemas(system_texts: &[String]) -> Vec<ToolSchema> {
    let mut seen = HashSet::new();
    let mut out = Vec::new();
    for text in system_texts {
        let Some(json) = extract_json_object(text) else {
            continue;
        };
        let Ok(schema): Result<ToolSchema, _> = serde_json::from_str(&json) else {
            continue;
        };
        if schema.name.is_empty() || seen.contains(&schema.name) {
            continue;
        }
        seen.insert(schema.name.clone());
        out.push(schema);
    }
    out
}

/// Unique identifier base for tool anchor nodes. Tool nodes use IDs above any
/// realistic token/sense space so they never collide with vocabulary nodes.
const TOOL_ANCHOR_BASE: u64 = 10_000_000_000;
const TOOL_ARG_BASE: u64 = 20_000_000_000;

/// Properties tag for a tool anchor node.
pub const PROP_TOOL_ANCHOR: &str = "tool_anchor";
/// Properties tag for a tool argument node.
pub const PROP_TOOL_ARG: &str = "tool_arg";

/// Inject tool schema subgraphs into an existing graph.
///
/// For each tool:
///   - create an anchor node tagged with the schema,
///   - create argument nodes for each parameter,
///   - link anchor → argument with high-weight edges.
///
/// Anchor positions are placed at the centroid of the token sense nodes that
/// spell the tool name, falling back to a position in the tool domain region if
/// no senses are found.
pub fn inject_tool_subgraphs(
    graph: &mut Vec<GraphNode4D>,
    schemas: &[ToolSchema],
    tokenizer: &tokenizers::Tokenizer,
    domain_centroid: Option<Vec3>,
) -> Result<()> {
    let node_index = graph
        .iter()
        .enumerate()
        .map(|(i, n)| (n.id, i))
        .collect::<HashMap<_, _>>();

    let mut next_anchor_id = TOOL_ANCHOR_BASE;
    let mut next_arg_id = TOOL_ARG_BASE;

    let fallback_centroid = domain_centroid.unwrap_or_else(|| {
        // Centroid of existing graph nodes.
        let mut sum = Vec3::ZERO;
        for node in graph.iter() {
            sum += node.position();
        }
        sum / graph.len().max(1) as f32
    });

    let n_schemas = schemas.len().max(1);
    // Spread tools that fall back to the domain centroid across a sphere so they
    // do not collapse to a single point.
    let fallback_radius = (n_schemas as f32).cbrt() * 0.3;

    for (idx, schema) in schemas.iter().enumerate() {
        // Find sense nodes for tool name tokens.
        let anchor_pos = centroid_for_text(graph, &node_index, tokenizer, &schema.name)
            .unwrap_or_else(|| {
                fibonacci_sphere_point(fallback_centroid, fallback_radius, idx, n_schemas)
            });

        let anchor_id = next_anchor_id;
        next_anchor_id += 1;

        let mut props = GraphProperties::new();
        props.insert(
            "type".to_string(),
            serde_json::Value::String(PROP_TOOL_ANCHOR.to_string()),
        );
        props.insert(
            "name".to_string(),
            serde_json::Value::String(schema.name.clone()),
        );
        props.insert(
            "schema".to_string(),
            serde_json::to_value(schema).context("failed to serialize tool schema")?,
        );

        let anchor = GraphNode4D {
            id: anchor_id,
            x: anchor_pos.x,
            y: anchor_pos.y,
            z: anchor_pos.z,
            begin_ts: 0,
            end_ts: u64::MAX,
            properties: props,
            successors: Vec::new(),
        };
        graph.push(anchor);
        let anchor_graph_idx = graph.len() - 1;

        // Argument nodes arranged radially around the anchor.
        let params: Vec<String> = schema.required_params();
        let n = params.len().max(1) as f32;
        for (i, param) in params.iter().enumerate() {
            let angle = 2.0 * std::f32::consts::PI * (i as f32) / n;
            let radius = 0.5;
            let offset = Vec3::new(angle.cos() * radius, angle.sin() * radius, 0.0);
            let arg_pos = anchor_pos + offset;

            let arg_id = next_arg_id;
            next_arg_id += 1;

            let mut arg_props = GraphProperties::new();
            arg_props.insert(
                "type".to_string(),
                serde_json::Value::String(PROP_TOOL_ARG.to_string()),
            );
            arg_props.insert(
                "tool".to_string(),
                serde_json::Value::String(schema.name.clone()),
            );
            arg_props.insert("arg".to_string(), serde_json::Value::String(param.clone()));

            let arg = GraphNode4D {
                id: arg_id,
                x: arg_pos.x,
                y: arg_pos.y,
                z: arg_pos.z,
                begin_ts: 0,
                end_ts: u64::MAX,
                properties: arg_props,
                successors: Vec::new(),
            };
            graph.push(arg);

            // Anchor -> argument edge.
            graph[anchor_graph_idx].successors.push(TemporalEdge {
                dst: arg_id,
                weight: 1.0,
                begin_ts: 0,
                end_ts: u64::MAX,
            });
        }
    }

    Ok(())
}

/// Deterministic point on a sphere using a Fibonacci lattice.
fn fibonacci_sphere_point(center: Vec3, radius: f32, index: usize, total: usize) -> Vec3 {
    let phi = (1.0 + 5.0f32.sqrt()) / 2.0;
    let y = 1.0 - (2.0 * index as f32 + 1.0) / total.max(1) as f32;
    let theta = 2.0 * std::f32::consts::PI * index as f32 / phi;
    let r = (1.0 - y * y).sqrt();
    let x = r * theta.cos();
    let z = r * theta.sin();
    center + Vec3::new(x, y, z) * radius
}

/// Compute the centroid of sense nodes for all tokens in `text`.
fn centroid_for_text(
    graph: &[GraphNode4D],
    node_index: &HashMap<u64, usize>,
    tokenizer: &tokenizers::Tokenizer,
    text: &str,
) -> Option<Vec3> {
    let encoding = tokenizer.encode(text.to_string(), false).ok()?;
    let token_ids: Vec<u32> = encoding.get_ids().to_vec();
    if token_ids.is_empty() {
        return None;
    }

    // Collect sense nodes for each token ID.
    let mut points = Vec::new();
    for &tid in &token_ids {
        let base = (tid as u64) * 1000;
        for sense_offset in 0..1000 {
            let node_id = base + sense_offset;
            if let Some(&idx) = node_index.get(&node_id) {
                points.push(graph[idx].position());
            }
        }
    }

    if points.is_empty() {
        return None;
    }

    let sum: Vec3 = points.iter().sum();
    Some(sum / points.len() as f32)
}

/// Load tool schemas that were persisted alongside a graph.
///
/// Properties may be stringified during binary persistence, so this function
/// handles both `Value::Object` and `Value::String(JSON)` forms.
pub fn load_persisted_tool_schemas(graph: &[GraphNode4D]) -> Vec<ToolSchema> {
    let mut out = Vec::new();
    let mut seen = HashSet::new();
    for node in graph {
        if node.properties.get("type").and_then(|v| v.as_str()) != Some(PROP_TOOL_ANCHOR) {
            continue;
        }
        let Some(name) = node.properties.get("name").and_then(|v| v.as_str()) else {
            continue;
        };
        if seen.contains(name) {
            continue;
        }
        let schema = node.properties.get("schema").and_then(|v| {
            let json = match v {
                serde_json::Value::String(s) => s.clone(),
                other => other.to_string(),
            };
            serde_json::from_str::<ToolSchema>(&json).ok()
        });
        if let Some(schema) = schema {
            seen.insert(name.to_string());
            out.push(schema);
        }
    }
    out
}

/// Find the tool anchor node closest to a position, if within `radius`.
pub fn nearest_tool_anchor(
    graph: &[GraphNode4D],
    position: Vec3,
    radius: f32,
) -> Option<(usize, ToolSchema)> {
    nearest_tool_anchor_scored(graph, position, radius, &[], None)
}

/// Find a tool anchor near `position`, ranking candidates by token overlap with
/// the prompt. Falls back to pure spatial proximity if no overlap is found.
pub fn nearest_tool_anchor_for_prompt(
    graph: &[GraphNode4D],
    position: Vec3,
    radius: f32,
    prompt_tokens: &[u32],
    tokenizer: &tokenizers::Tokenizer,
) -> Option<(usize, ToolSchema)> {
    nearest_tool_anchor_scored(graph, position, radius, prompt_tokens, Some(tokenizer))
}

fn nearest_tool_anchor_scored(
    graph: &[GraphNode4D],
    position: Vec3,
    radius: f32,
    prompt_tokens: &[u32],
    tokenizer: Option<&tokenizers::Tokenizer>,
) -> Option<(usize, ToolSchema)> {
    let prompt_set: std::collections::HashSet<u32> = prompt_tokens.iter().copied().collect();

    let mut best = None;
    let mut best_score = 0i32;
    let mut best_dist = f32::MAX;

    for (i, node) in graph.iter().enumerate() {
        if node.properties.get("type").and_then(|v| v.as_str()) != Some(PROP_TOOL_ANCHOR) {
            continue;
        }
        let dist = node.position().distance(position);
        if dist > radius {
            continue;
        }

        let name = node
            .properties
            .get("name")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        let overlap = tokenizer
            .and_then(|t| t.encode(name.to_string(), false).ok())
            .map(|enc| {
                enc.get_ids()
                    .iter()
                    .filter(|tid| prompt_set.contains(tid))
                    .count() as i32
            })
            .unwrap_or(0);

        // Prefer overlap, break ties by distance.
        let improve = match best {
            None => true,
            Some(_) if overlap > best_score => true,
            Some(_) if overlap == best_score && dist < best_dist => true,
            _ => false,
        };

        if improve {
            best = Some((i, node));
            best_score = overlap;
            best_dist = dist;
        }
    }

    let (idx, node) = best?;
    node.properties
        .get("schema")
        .and_then(|v| {
            let json = match v {
                serde_json::Value::String(s) => s.clone(),
                other => other.to_string(),
            };
            serde_json::from_str::<ToolSchema>(&json).ok()
        })
        .map(|schema| (idx, schema))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::algorithms::four_d::GraphProperties;

    fn make_node(id: u64, x: f32, y: f32, z: f32) -> GraphNode4D {
        GraphNode4D {
            id,
            x,
            y,
            z,
            begin_ts: 0,
            end_ts: u64::MAX,
            properties: GraphProperties::new(),
            successors: Vec::new(),
        }
    }

    #[test]
    fn extract_json_object_finds_nested_object() {
        let text = r#"SYSTEM: you have functions -
{"name":"get_rate","description":"x","parameters":{"type":"object","properties":{"base":{"type":"string"}},"required":["base"]}}
more text"#;
        let json = extract_json_object(text).unwrap();
        assert!(json.contains("\"name\":\"get_rate\""));
        let schema: ToolSchema = serde_json::from_str(&json).unwrap();
        assert_eq!(schema.name, "get_rate");
        assert_eq!(schema.required_params(), vec!["base"]);
    }

    #[test]
    fn parse_tool_schemas_deduplicates() {
        let texts = vec![
            "{\"name\":\"a\",\"parameters\":{}}".to_string(),
            "{\"name\":\"a\",\"parameters\":{}}".to_string(),
            "{\"name\":\"b\",\"parameters\":{}}".to_string(),
        ];
        let schemas = parse_tool_schemas(&texts);
        assert_eq!(schemas.len(), 2);
    }

    #[test]
    fn load_persisted_tool_schemas_roundtrips() {
        let schema = ToolSchema {
            name: "foo".to_string(),
            description: "bar".to_string(),
            parameters: serde_json::json!({"required": ["x"]}),
        };
        let mut props = GraphProperties::new();
        props.insert(
            "type".to_string(),
            serde_json::Value::String(PROP_TOOL_ANCHOR.to_string()),
        );
        props.insert(
            "name".to_string(),
            serde_json::Value::String("foo".to_string()),
        );
        props.insert("schema".to_string(), serde_json::to_value(&schema).unwrap());
        let node = GraphNode4D {
            id: TOOL_ANCHOR_BASE,
            x: 0.0,
            y: 0.0,
            z: 0.0,
            begin_ts: 0,
            end_ts: u64::MAX,
            properties: props,
            successors: Vec::new(),
        };
        let loaded = load_persisted_tool_schemas(&[node]);
        assert_eq!(loaded.len(), 1);
        assert_eq!(loaded[0].name, "foo");
    }

    #[test]
    fn tool_anchor_persists_through_save_load() {
        let dir = tempfile::tempdir().unwrap();
        let mut graph = vec![make_node(0, 0.0, 0.0, 0.0), make_node(1, 1.0, 0.0, 0.0)];
        let schema = ToolSchema {
            name: "get_rate".to_string(),
            description: "".to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {"base": {"type": "string"}},
                "required": ["base"]
            }),
        };

        // Build a fake tokenizer that maps "get_rate" to token id 7.
        let mut tokenizer = tokenizers::Tokenizer::new(tokenizers::models::bpe::BPE::default());
        tokenizer.add_tokens(&[tokenizers::AddedToken::from("get_rate".to_string(), false)]);

        inject_tool_subgraphs(&mut graph, &[schema], &tokenizer, None).unwrap();
        crate::save_graph4d(&graph, dir.path()).unwrap();
        let loaded = crate::load_graph4d(dir.path()).unwrap();

        let schemas = load_persisted_tool_schemas(&loaded);
        assert_eq!(schemas.len(), 1);
        assert_eq!(schemas[0].name, "get_rate");
        assert_eq!(schemas[0].required_params(), vec!["base"]);

        let anchor = nearest_tool_anchor(&loaded, Vec3::new(0.0, 0.0, 0.0), 10.0);
        assert!(anchor.is_some());
    }
}