# geographdb-core API

This document summarizes the public API surface. Rustdoc remains the source of truth for exact signatures.

## Crate Root

The crate root re-exports common graph-analysis and storage types:

- `CfgGraphNode`, `CfgPath`, `PathComplexity`
- `ComplexityBlock`, `ComplexityRating`, `ComplexityResult`
- `DominanceResult`, `compute_dominance`, `compute_dominance_frontier`
- `LoopAnalysisResult`, `LoopBlock`, `LoopInfo`
- `NaturalLoop`, `find_back_edges`, `find_natural_loops`
- `SccResult`, `tarjan_scc`, `find_cycles`, `has_cycles`, `condense_graph`
- `SliceResult`, `forward_slice`, `backward_slice`
- `TopoResult`, `TopoError`, `topological_sort`, `is_dag`, `critical_path_length`
- `ReachabilityResult`, `transitive_closure`, `transitive_reduction`
- `GraphNode4D`, `GraphProperties`, `TemporalEdge`, `TemporalJourney4D`, `TemporalWindow`, `SpatialRegion`, `TraversalContext4D`
- `GraphPath4D`, `reachable_4d`, `astar_find_path_4d`, `strongly_connected_components_4d`
- `articulation_points_4d`, `bridges_4d`
- `TemporalArrival4D`, `TemporalDijkstraResult4D`, `time_dependent_dijkstra_4d`
- `earliest_arrival_path_4d`, `fastest_temporal_path_4d`
- `save_graph4d`, `load_graph4d`, `PropertyValue`, `PropStore`
- Sectioned storage types and sidecar path helpers
- `query_4d`, `GeoCypherResult`, `GeoCypherRow`, `GeoCypherError`

## `spatial`

Spatial primitives for indexing code and graph entities in 3D.

Key types:

- `BoundingBox` - axis-aligned 3D bounds.
- `Octree` - spatial index for `NodePoint` values.
- `OctreeQueryStats` - traversal metrics for spatial queries.
- `MortonEncode` - Morton/Z-order encoding helper.

Common operations:

```rust
use geographdb_core::spatial::{BoundingBox, Octree};
use geographdb_core::storage::NodePoint;
use glam::Vec3;

let bounds = BoundingBox::new(Vec3::ZERO, Vec3::splat(100.0));
let mut octree = Octree::new(bounds);

octree.insert(NodePoint { id: 7, x: 1.0, y: 2.0, z: 3.0 });
let nearby = octree.query_sphere(Vec3::new(1.0, 2.0, 3.0), 4.0);
```

## `storage`

Storage primitives for `.geo` and sidecar files.

Key types:

- `NodePoint`, `NodeRec`, `EdgeRec`, `MetadataRec`
- `StorageManager`, `GraphStorageManager`
- `SectionedStorage`, `GeoFileHeader`, `Section`, `SectionEntry`
- `GraphSectionAdapter`, `GraphData`
- `CfgSectionAdapter`, `CfgData`, `CfgEdge`, `SerializableCfgBlock`
- `SymbolMetadataSectionAdapter`, `SymbolMetadataStore`
- `Wal`, `WalEntry`, `WalEntryType`
- `PropertyValue`, `PropStore`, `NodeProperties`, `PropLookupEntry`
- `DualOctree` (persisted dual octree for spatial indexing)

Sidecar helpers:

- `geo_cfg_path(base_geo)`
- `geo_idx_path(base_geo)`
- `geo_complexity_path(base_geo)`
- `all_sidecar_paths(base_geo)`

## `cfg_store`

High-level storage for CFG blocks using both persistent records and an in-memory octree.

Key types:

- `CfgBlock`
- `CfgBlockMetadata`
- `CfgStore`

Common flow:

```rust
use geographdb_core::cfg_store::{CfgBlock, CfgStore};
use glam::Vec3;

let path = tempfile::tempdir().unwrap().path().join("code.geo");
let mut store = CfgStore::create(&path).unwrap();

store.insert_block(CfgBlock {
    id: 1,
    function_id: 42,
    block_kind: "entry".to_string(),
    terminator: "goto".to_string(),
    byte_start: 0,
    byte_end: 10,
    start_line: 1,
    start_col: 0,
    end_line: 1,
    end_col: 10,
    dominator_depth: 0,
    loop_nesting: 0,
    branch_count: 0,
}).unwrap();

let blocks = store.query_nearby(Vec3::new(0.0, 0.0, 42.0), 1.0);
assert_eq!(blocks.len(), 1);
```

## `algorithms`

Graph and CFG algorithms used by the geometric backend:

- `astar` - path search and path complexity primitives.
- `complexity` - block and path complexity classification.
- `dominance` - dominators and dominance frontier.
- `loop_detection` and `natural_loops` - loop analysis.
- `scc` - strongly connected components and cycle checks.
- `slicing` - forward and backward graph slicing.
- `topo_sort` - DAG checks and topological ordering.
- `transitive` - transitive closure and reduction.
- `four_d` - traversal over graph nodes/edges with temporal validity and optional 3D spatial filters.

### `algorithms::four_d`

4D algorithms use `GraphNode4D` and `TemporalEdge` instead of changing the existing
`CfgGraphNode` API.

Key types:

- `GraphNode4D` - node ID, 3D position, temporal validity interval, user properties, and temporal edges.
- `GraphProperties` - `BTreeMap<String, serde_json::Value>` metadata attached to a 4D node.
- `TemporalEdge` - destination, weight, and edge validity interval.
- `TemporalWindow` - half-open query window; `end_ts = 0` on records is treated as open-ended.
- `SpatialRegion` - sphere or axis-aligned bounding box filter.
- `TraversalContext4D` - query context with optional time/space filters and graph/spatial/temporal weights.
- `GraphPath4D` - A* result path and cost breakdown.
- `TemporalJourney4D` - time-respecting path with departure, arrival, and duration.

Common operations:

- `reachable_4d(nodes, start_id, ctx)` - BFS reachability constrained by time and space.
- `astar_find_path_4d(nodes, start_id, goal_id, ctx)` - path search using graph edge cost plus optional spatial/temporal penalties.
- `strongly_connected_components_4d(nodes, ctx)` - SCCs after applying temporal and spatial eligibility.
- `articulation_points_4d(nodes, ctx)` - articulation points in the active 4D induced graph.
- `bridges_4d(nodes, ctx)` - bridge edges in the active 4D induced graph.
- `time_dependent_dijkstra_4d(nodes, start_id, departure_time, spatial_region)` - single-source earliest-arrival propagation over scheduled edges.
- `earliest_arrival_path_4d(nodes, start_id, goal_id, departure_time, spatial_region)` - earliest time-respecting journey after departure.
- `fastest_temporal_path_4d(nodes, start_id, goal_id, earliest_departure, latest_departure, spatial_region)` - shortest-duration journey over a departure range.

## `cypher_4d`

A deliberately small Cypher-like query dispatcher for 4D graph slices. It is not
full Neo4j Cypher; it parses a practical subset and dispatches to the public
4D APIs.

Supported first-pass forms:

```cypher
MATCH (a)-[:CONNECTS]->(b) RETURN a, b
MATCH (a)-[:CONNECTS]->(b) RETURN a.name, b.name
MATCH (a)-[:CONNECTS]->(b) WHERE time_window(10, 60) RETURN a, b
MATCH (a)-[:CONNECTS]->(b) WHERE spatial_sphere([0.0, 0.0, 0.0], 5.0) RETURN a, b
CALL db.route.temporal(1, 6, departure: 10) YIELD path, arrival_time, duration RETURN path, arrival_time
CALL db.impact.radius(10, spatial_sphere([0,0,0], 5.0), time_window(50, 60)) YIELD reachable RETURN reachable
```

Common entrypoint:

- `query_4d(nodes, query)` - parses the query and returns `GeoCypherResult`.
- `GeoCypherResult::Rows` - returned for property projections such as `a.name`
  and `b.name`; built-in fields such as `id`, `x`, `y`, `z`, `begin_ts`, and
  `end_ts` can also be projected.

Runnable examples:

- `cargo run --example demo_4d_dependency_timeline`
- `cargo run --example demo_4d_cypher_bottlenecks`
- `cargo run --example demo_4d_cypher_impact_radius`
- `cargo run --example demo_4d_cypher_match_filters`
- `cargo run --example demo_4d_cypher_queries`
- `cargo run --example demo_4d_cypher_signal_propagation`
- `cargo run --example demo_4d_cypher_temporal_route`
- `cargo run --example demo_4d_impact_radius`
- `cargo run --example demo_4d_route_planning`
- `cargo run --example demo_4d_signal_propagation`
- `cargo run --example demo_4d_temporal_bottlenecks`
- `cargo run --example demo_4d_temporal_delivery`

Append `-- --json` to emit a structured JSON result from any demo. For example:

```bash
cargo run --quiet --example demo_4d_route_planning -- --json > route-planning.json
```

## Compatibility

`geographdb-core` is independent from Magellan's SQLite schema. Magellan owns schema ingestion and can use this crate as an optional geometric backend for spatial CFG storage and analysis.
