# geographdb-core

3D spatial indexing and graph-storage primitives for CFG and graph analysis.

This crate provides octree indexing, Morton ordering, sectioned storage, CFG block storage, and graph algorithms for tools that model control-flow and graph structure geometrically.

## Features

- Octree spatial indexing for 3D points and bounding boxes
- Morton code ordering for cache-friendly spatial locality
- Sectioned storage for graph, symbol, and CFG records
- CFG-oriented storage and query helpers
- Graph algorithms including A*, SCC, dominance, loops, slicing, and topological ordering
- 4D traversal primitives that combine graph topology, 3D spatial filters, and temporal validity windows
- Small Cypher-like 4D query layer for pattern, routing, and impact queries

## Code-Intelligence Use Case

Magellan stores control-flow blocks in 3D space:

- X = structural or dominance depth
- Y = loop nesting level
- Z = function or path grouping dimension

Tools can then query control-flow structure using geometric locality.

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

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

octree.insert(NodePoint { id: 1, x: 0.0, y: 0.0, z: 42.0 });
octree.insert(NodePoint { id: 2, x: 1.0, y: 0.0, z: 42.0 });
octree.insert(NodePoint { id: 3, x: 2.0, y: 1.0, z: 42.0 });

let nearby = octree.query_sphere(Vec3::new(1.0, 0.0, 42.0), 2.0);
assert_eq!(nearby.len(), 3);
```

## 4D Graph Traversal

Use the 4D algorithm API when a graph edge or node should only participate in a
query inside a spatial region and temporal window.

```rust
use geographdb_core::{
    astar_find_path_4d, GraphNode4D, TemporalEdge, TemporalWindow, TraversalContext4D,
};

let nodes = vec![
    GraphNode4D {
        id: 1,
        x: 0.0,
        y: 0.0,
        z: 42.0,
        begin_ts: 0,
        end_ts: 100,
        properties: Default::default(),
        successors: vec![TemporalEdge {
            dst: 2,
            weight: 1.0,
            begin_ts: 0,
            end_ts: 100,
        }],
    },
    GraphNode4D {
        id: 2,
        x: 1.0,
        y: 0.0,
        z: 42.0,
        begin_ts: 0,
        end_ts: 100,
        properties: Default::default(),
        successors: vec![],
    },
];

let ctx = TraversalContext4D {
    time_window: Some(TemporalWindow { start: 10, end: 20 }),
    spatial_region: None,
    graph_weight: 1.0,
    spatial_weight: 0.5,
    temporal_weight: 0.0,
};

let path = astar_find_path_4d(&nodes, 1, 2, &ctx).unwrap();
assert_eq!(path.node_ids, vec![1, 2]);
```

`GraphNode4D::properties` is a JSON metadata map. The 4D Cypher-like layer can
project those values directly with queries such as
`MATCH (a)-[:CONNECTS]->(b) RETURN a.name, b.name`.

## Persistence

`save_graph4d` and `load_graph4d` round-trip a full 4D graph through the
`GraphStorageManager`, persisting nodes, edges, the dual octree spatial index,
and typed node properties to a `.geo` archive.

```rust
use geographdb_core::{save_graph4d, load_graph4d};

let file = std::fs::File::create("graph.geo")?;
save_graph4d(file, &nodes)?;

let file = std::fs::File::open("graph.geo")?;
let loaded = load_graph4d(file)?;
```

## Installation

```toml
[dependencies]
geographdb-core = "0.3"
```

For local development with Magellan:

```toml
geographdb-core = { path = "../geographdb-core" }
```

## Runnable 4D Demos

The crate includes runnable 4D graph demos: temporal dependencies,
constrained impact analysis, route adaptation, time-respecting delivery, signal
propagation, dynamic bottleneck resilience, orbit constellation, metamaterial
design, and protein conformation.

Together they show standard graph questions upgraded with temporal validity and
3D spatial context:

```bash
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_disaster_response
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
cargo run --example demo_4d_orbit_constellation
cargo run --example demo_4d_metamaterial_design
cargo run --example demo_4d_protein_conformation
```

Each demo can also export a JSON result for repeatable checks or reports:

```bash
cargo run --quiet --example demo_4d_dependency_timeline -- --json > dependency-timeline.json
cargo run --quiet --example demo_4d_cypher_bottlenecks -- --json > cypher-bottlenecks.json
cargo run --quiet --example demo_4d_cypher_impact_radius -- --json > cypher-impact-radius.json
cargo run --quiet --example demo_4d_cypher_match_filters -- --json > cypher-match-filters.json
cargo run --quiet --example demo_4d_cypher_queries -- --json > cypher-queries.json
cargo run --quiet --example demo_4d_cypher_disaster_response -- --json > cypher-disaster-response.json
cargo run --quiet --example demo_4d_cypher_signal_propagation -- --json > cypher-signal-propagation.json
cargo run --quiet --example demo_4d_cypher_temporal_route -- --json > cypher-temporal-route.json
cargo run --quiet --example demo_4d_impact_radius -- --json > impact-radius.json
cargo run --quiet --example demo_4d_route_planning -- --json > route-planning.json
cargo run --quiet --example demo_4d_signal_propagation -- --json > signal-propagation.json
cargo run --quiet --example demo_4d_temporal_bottlenecks -- --json > temporal-bottlenecks.json
cargo run --quiet --example demo_4d_temporal_delivery -- --json > temporal-delivery.json
cargo run --quiet --example demo_4d_orbit_constellation -- --json > orbit-constellation.json
cargo run --quiet --example demo_4d_metamaterial_design -- --json > metamaterial-design.json
cargo run --quiet --example demo_4d_protein_conformation -- --json > protein-conformation.json
```

Sample outputs are stored under `examples/results/`.

- `demo_4d_cypher_queries` shows a small Cypher-like layer for `MATCH`,
  property projections, `WHERE time_window(...)`, `WHERE spatial_sphere(...)`,
  and `CALL db.*` procedure queries.
- `demo_4d_cypher_match_filters`, `demo_4d_cypher_temporal_route`,
  `demo_4d_cypher_impact_radius`, `demo_4d_cypher_bottlenecks`, and
  `demo_4d_cypher_signal_propagation` split that query layer into focused,
  copyable scenarios.
- `demo_4d_dependency_timeline` compares reachability, path search, and SCCs
  before and after a dependency graph changes over time.
- `demo_4d_impact_radius` compares topology-only impact analysis with the same
  query constrained to a local 3D region and a current time window.
- `demo_4d_route_planning` shows A* selecting a different route when the direct
  corridor is no longer valid in the requested time window.
- `demo_4d_signal_propagation` shows a time-dependent Dijkstra arrival wave
  from one source across scheduled links.
- `demo_4d_temporal_bottlenecks` shows critical relays and links disappearing
  after a temporary relay creates redundancy.
- `demo_4d_temporal_delivery` shows causal temporal routing where edge schedules
  determine whether the next hop is possible after arrival.

## Scope

This crate contains the Rust core used for spatial CFG and graph storage. Language bindings and larger application crates are separate packages.

## Public API Areas

- `spatial`: `Octree`, `BoundingBox`, Morton encoding, and SIMD distance filtering.
- `storage`: sectioned `.geo` storage, sidecar path helpers, graph/CFG/symbol
  section adapters, WAL records, dual octree spatial indexing,
  `GraphStorageManager`, and the `prop_store` binary typed-property format.
- `cfg_store`: high-level CFG block storage backed by spatial indexing.
- `algorithms`: graph algorithms for CFG analysis and path reasoning.
- Persistence via `save_graph4d` and `load_graph4d` for full 4D graph round-trips.

## Feature Flags

- `telemetry`: enables tracing and dashmap-backed instrumentation helpers.
- `debug-prints`: enables debug instrumentation points used during local investigation.

## Documentation

- [API.md](API.md) describes the public modules and common types.
- [MANUAL.md](MANUAL.md) covers local development, verification, and publishing.
- [CHANGELOG.md](CHANGELOG.md) records release changes.

## Verification

```bash
cargo check
cargo test
cargo publish --dry-run
cargo package --list
```

## License

GPL-3.0-only. See [LICENSE](LICENSE).
