1use super::{EffectClass, HonestyLabel, SchemaArg, SchemaEntry};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15pub enum Effect {
16 Pure, Compute, Cold, Async, External,
17}
18
19impl Effect {
20 pub const fn as_str(&self) -> &'static str {
21 match self {
22 Self::Pure => "pure", Self::Compute => "compute", Self::Cold => "cold",
23 Self::Async => "async", Self::External => "external",
24 }
25 }
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30pub enum ParamType {
31 F64, I64, U64, Bool, Str, Record, List, FieldRef, GeometryRef,
32}
33
34impl ParamType {
35 pub const fn as_str(&self) -> &'static str {
36 match self {
37 Self::F64 => "f64", Self::I64 => "i64", Self::U64 => "u64", Self::Bool => "bool",
38 Self::Str => "string", Self::Record => "Record", Self::List => "List",
39 Self::FieldRef => "FieldRef", Self::GeometryRef => "GeometryRef",
40 }
41 }
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub struct ParamSchema {
47 pub name: &'static str,
48 pub param_type: ParamType,
49 pub required: bool,
50 pub description: &'static str,
51}
52
53const fn p(name: &'static str, ty: ParamType, req: bool, desc: &'static str) -> ParamSchema {
54 ParamSchema { name, param_type: ty, required: req, description: desc }
55}
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub struct OperationSchema {
60 pub invoke_id: &'static str,
61 pub effect: Effect,
62 pub params: &'static [ParamSchema],
63 pub returns: &'static str,
64 pub description: &'static str,
65}
66
67const fn op(id: &'static str, eff: Effect, ret: &'static str, desc: &'static str, params: &'static [ParamSchema]) -> OperationSchema {
68 OperationSchema { invoke_id: id, effect: eff, params, returns: ret, description: desc }
69}
70
71pub const OP_OBLIGATE: u8 = 0x10;
73pub const OP_PERMIT: u8 = 0x11;
74pub const OP_FORBID: u8 = 0x12;
75
76pub const DEFEATER_BIT: u64 = 1u64 << 63;
78
79#[derive(Debug, Clone, PartialEq)]
81pub struct SpatialCovenantZoneDecl {
82 pub zone_id: String,
83 pub covenant_type: String,
84 pub deontic_opcode: u8,
85 pub is_defeater: bool,
86 pub buffer_distance_m: f64,
87 pub priority: u32,
88}
89
90impl SpatialCovenantZoneDecl {
91 pub fn new(
92 zone_id: impl Into<String>, covenant_type: impl Into<String>,
93 deontic_opcode: u8, is_defeater: bool, buffer_distance_m: f64, priority: u32,
94 ) -> Self {
95 Self {
96 zone_id: zone_id.into(), covenant_type: covenant_type.into(),
97 deontic_opcode, is_defeater, buffer_distance_m, priority,
98 }
99 }
100
101 pub fn validate(&self) -> Result<(), &'static str> {
102 if self.zone_id.is_empty() { return Err("zone_id must not be empty"); }
103 if self.covenant_type.is_empty() { return Err("covenant_type must not be empty"); }
104 if !matches!(self.deontic_opcode, OP_OBLIGATE | OP_PERMIT | OP_FORBID) {
105 return Err("deontic_opcode must be 0x10, 0x11, or 0x12");
106 }
107 if self.buffer_distance_m < 0.0 { return Err("buffer_distance_m must not be negative"); }
108 Ok(())
109 }
110}
111
112pub const GEO_SPARQL_DEONTIC_INVOKE_IDS: &[&str] = &[
114 "GeoSparql.de9im_matrix", "GeoSparql.sf_equals", "GeoSparql.sf_disjoint",
115 "GeoSparql.sf_intersects", "GeoSparql.sf_touches", "GeoSparql.sf_within",
116 "GeoSparql.sf_contains", "GeoSparql.sf_overlaps", "GeoSparql.distance",
117 "GeoSparql.mint_spatial_quin", "GeoSparql.evaluate_deontic_covenant",
118 "GisIo.query_ogc_features_cql2", "GisIo.query_wfs_arcgis_csw", "GisIo.query_stac_catalog",
119 "GisIo.query_sensorthings_sos", "GisIo.plan_cog_range_read", "GisIo.query_wcs_wms_wmts",
120 "GisIo.read_zarr_netcdf_grib", "GisIo.compile_datacube_10d",
121];
122
123pub const GEO_SPARQL_DEONTIC_OPERATIONS: &[OperationSchema] = &[
125 op("GeoSparql.de9im_matrix", Effect::Pure, "Str", "Compute 9-character DE-9IM intersection matrix between two geometries.", &[
126 p("geom_a", ParamType::GeometryRef, true, "First geometry operand"),
127 p("geom_b", ParamType::GeometryRef, true, "Second geometry operand"),
128 ]),
129 op("GeoSparql.sf_equals", Effect::Pure, "Bool", "Evaluate topological equality predicate sfEquals (DE-9IM T*F**FFF*).", &[
130 p("geom_a", ParamType::GeometryRef, true, "First geometry operand"),
131 p("geom_b", ParamType::GeometryRef, true, "Second geometry operand"),
132 ]),
133 op("GeoSparql.sf_disjoint", Effect::Pure, "Bool", "Evaluate topological disjointness predicate sfDisjoint (DE-9IM FF*FF****).", &[
134 p("geom_a", ParamType::GeometryRef, true, "First geometry operand"),
135 p("geom_b", ParamType::GeometryRef, true, "Second geometry operand"),
136 ]),
137 op("GeoSparql.sf_intersects", Effect::Pure, "Bool", "Evaluate topological intersection predicate sfIntersects (DE-9IM !FF*FF****).", &[
138 p("geom_a", ParamType::GeometryRef, true, "First geometry operand"),
139 p("geom_b", ParamType::GeometryRef, true, "Second geometry operand"),
140 ]),
141 op("GeoSparql.sf_touches", Effect::Pure, "Bool", "Evaluate topological boundary touch predicate sfTouches.", &[
142 p("geom_a", ParamType::GeometryRef, true, "First geometry operand"),
143 p("geom_b", ParamType::GeometryRef, true, "Second geometry operand"),
144 ]),
145 op("GeoSparql.sf_within", Effect::Pure, "Bool", "Evaluate topological within predicate sfWithin (DE-9IM T*F**F***).", &[
146 p("geom_a", ParamType::GeometryRef, true, "Candidate interior geometry"),
147 p("geom_b", ParamType::GeometryRef, true, "Target enclosing geometry"),
148 ]),
149 op("GeoSparql.sf_contains", Effect::Pure, "Bool", "Evaluate topological spatial containment predicate sfContains (DE-9IM T*****FF*).", &[
150 p("geom_a", ParamType::GeometryRef, true, "Target enclosing geometry"),
151 p("geom_b", ParamType::GeometryRef, true, "Candidate interior geometry"),
152 ]),
153 op("GeoSparql.sf_overlaps", Effect::Pure, "Bool", "Evaluate topological spatial overlap predicate sfOverlaps (DE-9IM T*T***T**).", &[
154 p("geom_a", ParamType::GeometryRef, true, "First geometry operand"),
155 p("geom_b", ParamType::GeometryRef, true, "Second geometry operand"),
156 ]),
157 op("GeoSparql.distance", Effect::Pure, "F64", "Compute minimum distance between geometries in meters.", &[
158 p("geom_a", ParamType::GeometryRef, true, "First geometry operand"),
159 p("geom_b", ParamType::GeometryRef, true, "Second geometry operand"),
160 p("crs", ParamType::Str, false, "Coordinate reference system (default EPSG:7855)"),
161 ]),
162 op("GeoSparql.mint_spatial_quin", Effect::Pure, "Record", "Mint 48B NQuin with deontic opcode (0x10..0x12) and defeater bit.", &[
163 p("subject_did", ParamType::Str, true, "Subject entity or place DID"),
164 p("predicate_iri", ParamType::Str, true, "Predicate norm IRI"),
165 p("object_ref", ParamType::Record, true, "Target geometry or resource payload reference"),
166 p("deontic_opcode", ParamType::U64, true, "Deontic opcode: 0x10 (Obligate), 0x11 (Permit), 0x12 (Forbid)"),
167 p("is_defeater", ParamType::Bool, true, "Defeater rule flag (^> vs ~>) encoded into predicate MSB"),
168 p("context_zone", ParamType::Str, true, "Covenant context zone DID or graph IRI"),
169 ]),
170 op("GeoSparql.evaluate_deontic_covenant", Effect::Pure, "Record", "Evaluate DE-9IM intersection against covenant zones and resolve defeasible rules.", &[
171 p("proposed_geom", ParamType::GeometryRef, true, "Proposed activity or infrastructure footprint geometry"),
172 p("covenant_zones", ParamType::List, true, "List of active SpatialCovenantZone protection records"),
173 p("context", ParamType::Record, false, "Evaluation context with requester credentials and epoch"),
174 ]),
175 op("GisIo.query_ogc_features_cql2", Effect::External, "Record", "Query OGC API Features endpoint with CQL2 filter.", &[
176 p("url", ParamType::Str, true, "OGC API Features service endpoint URL"),
177 p("collection_id", ParamType::Str, true, "Feature collection identifier"),
178 p("cql2_filter", ParamType::Str, true, "CQL2-JSON or CQL2-Text query filter expression"),
179 p("bbox", ParamType::Record, false, "Spatial bounding box filter record"),
180 p("limit", ParamType::U64, false, "Maximum feature limit per page"),
181 ]),
182 op("GisIo.query_wfs_arcgis_csw", Effect::External, "Record", "Query WFS 2.0, ArcGIS REST FeatureServer, or CSW 3.0 catalog.", &[
183 p("service_url", ParamType::Str, true, "Base service endpoint URL"),
184 p("service_type", ParamType::Str, true, "Service type selector (wfs, arcgis, csw)"),
185 p("type_names", ParamType::Str, true, "Feature type names or catalog layer name"),
186 p("filter_xml_json", ParamType::Str, false, "OGC XML filter or ArcGIS JSON where clause"),
187 p("bbox", ParamType::Record, false, "Spatial bounding box filter record"),
188 ]),
189 op("GisIo.query_stac_catalog", Effect::External, "Record", "Query STAC 1.0 catalog API search and select cloud-free COG assets.", &[
190 p("stac_url", ParamType::Str, true, "STAC API search endpoint URL"),
191 p("collections", ParamType::List, true, "Target collection IDs list"),
192 p("bbox", ParamType::Record, true, "Spatial bounding box filter record"),
193 p("datetime", ParamType::Str, false, "RFC 3339 datetime or interval string"),
194 p("max_cloud_cover", ParamType::F64, false, "Maximum cloud cover percentage threshold"),
195 ]),
196 op("GisIo.query_sensorthings_sos", Effect::External, "Record", "Query OGC SensorThings v1.1 API or SOS 2.0 observation stream.", &[
197 p("service_url", ParamType::Str, true, "SensorThings or SOS service root URL"),
198 p("observed_property", ParamType::Str, true, "Target observed property name or URN"),
199 p("temporal_range", ParamType::Str, false, "ISO 8601 temporal range filter"),
200 p("bbox", ParamType::Record, false, "Spatial bounding box filter record"),
201 ]),
202 op("GisIo.plan_cog_range_read", Effect::Pure, "Record", "Parse COG IFD headers and plan HTTP byte-range GET requests.", &[
203 p("cog_metadata", ParamType::Record, true, "Cloud-Optimized GeoTIFF IFD metadata record"),
204 p("target_bbox", ParamType::Record, true, "Target sub-window bounding box record"),
205 p("resolution_level", ParamType::U64, false, "Overview level (0 = full resolution)"),
206 ]),
207 op("GisIo.query_wcs_wms_wmts", Effect::External, "Record", "Query OGC WCS 2.0, axis-order-aware WMS 1.3.0, or WMTS 1.0 tile matrix.", &[
208 p("service_url", ParamType::Str, true, "OGC service endpoint URL"),
209 p("service_type", ParamType::Str, true, "Service type selector (wcs, wms, wmts)"),
210 p("layer", ParamType::Str, true, "Layer or coverage identifier"),
211 p("bbox", ParamType::Record, true, "Spatial bounding box filter record"),
212 p("crs", ParamType::Str, true, "Coordinate reference system"),
213 p("width", ParamType::U64, false, "Raster image pixel width"),
214 p("height", ParamType::U64, false, "Raster image pixel height"),
215 ]),
216 op("GisIo.read_zarr_netcdf_grib", Effect::Cold, "Record", "Unpack gridded environmental array data from Zarr v2/v3, NetCDF, or GRIB2.", &[
217 p("path", ParamType::Str, true, "File path or URL to .zarr, .nc, or .grib2 dataset"),
218 p("format", ParamType::Str, true, "Format selector (zarr, netcdf, grib2)"),
219 p("variable_names", ParamType::List, true, "Variable names to extract"),
220 p("temporal_slice", ParamType::Str, false, "Temporal index or timestamp range"),
221 p("byte_budget", ParamType::U64, false, "Maximum byte budget for buffer allocation"),
222 ]),
223 op("GisIo.compile_datacube_10d", Effect::Compute, "Record", "Compile multi-variable slices into 10D Environmental Tensor Cube with QUDT units.", &[
224 p("slices", ParamType::Record, true, "Input spatial and multi-variable slice records"),
225 p("spatial_extent", ParamType::Record, true, "Bounding spatial extent record"),
226 p("temporal_extent", ParamType::Record, true, "Temporal range and interval record"),
227 p("qudt_units", ParamType::List, true, "QUDT unit tokens list for tensor dimensions"),
228 ]),
229];
230
231pub fn lookup_geo_sparql_deontic_operation(invoke_id: &str) -> Option<&'static OperationSchema> {
233 GEO_SPARQL_DEONTIC_OPERATIONS.iter().find(|op| op.invoke_id == invoke_id)
234}
235
236pub fn entries() -> Vec<SchemaEntry> {
238 GEO_SPARQL_DEONTIC_OPERATIONS.iter().map(|op| {
239 let effect_class = match op.effect {
240 Effect::Pure => EffectClass::Pure,
241 Effect::Compute | Effect::Cold => EffectClass::Read,
242 Effect::Async | Effect::External => EffectClass::External,
243 };
244 let mut entry = SchemaEntry::new(op.invoke_id, effect_class, HonestyLabel::Always, op.returns)
245 .with_description(op.description);
246 for p in op.params {
247 entry = entry.with_arg(SchemaArg::new(p.name, p.param_type.as_str(), p.required).with_description(p.description));
248 }
249 entry
250 }).collect()
251}
252
253#[cfg(test)]
254mod tests {
255 use super::*;
256
257 #[test]
258 fn test_geo_sparql_deontic_operations_count_and_uniqueness() {
259 assert_eq!(GEO_SPARQL_DEONTIC_OPERATIONS.len(), 19);
260 assert_eq!(GEO_SPARQL_DEONTIC_INVOKE_IDS.len(), 19);
261 for (i, op) in GEO_SPARQL_DEONTIC_OPERATIONS.iter().enumerate() {
262 assert_eq!(op.invoke_id, GEO_SPARQL_DEONTIC_INVOKE_IDS[i]);
263 assert!(op.invoke_id.starts_with("GeoSparql.") || op.invoke_id.starts_with("GisIo."));
264 assert!(!op.returns.is_empty());
265 assert!(!op.description.is_empty());
266 }
267 let mut ids: Vec<&str> = GEO_SPARQL_DEONTIC_INVOKE_IDS.to_vec();
268 ids.sort();
269 ids.dedup();
270 assert_eq!(ids.len(), 19, "All 19 invoke IDs must be unique");
271 }
272
273 #[test]
274 fn test_entries_conversion_and_lookup() {
275 assert!(lookup_geo_sparql_deontic_operation("GeoSparql.de9im_matrix").is_some());
276 assert!(lookup_geo_sparql_deontic_operation("GeoSparql.mint_spatial_quin").is_some());
277 assert!(lookup_geo_sparql_deontic_operation("GeoSparql.evaluate_deontic_covenant").is_some());
278 assert!(lookup_geo_sparql_deontic_operation("GisIo.query_stac_catalog").is_some());
279 assert!(lookup_geo_sparql_deontic_operation("GisIo.plan_cog_range_read").is_some());
280 assert!(lookup_geo_sparql_deontic_operation("GisIo.compile_datacube_10d").is_some());
281 assert!(lookup_geo_sparql_deontic_operation("GeoSparql.unknown_operation").is_none());
282
283 let converted = entries();
284 assert_eq!(converted.len(), 19);
285 for (i, entry) in converted.iter().enumerate() {
286 assert_eq!(entry.id, GEO_SPARQL_DEONTIC_INVOKE_IDS[i]);
287 assert_eq!(entry.honesty, HonestyLabel::Always);
288 }
289 }
290
291 #[test]
292 fn test_spatial_covenant_zone_decl_validation() {
293 let valid_forbid = SpatialCovenantZoneDecl::new(
294 "urn:qualia:zone:sphagnum-bog-kosciuszko",
295 "IndigenousCulturalHeritageAndPeatlandSanctuary",
296 OP_FORBID, true, 150.0, 1,
297 );
298 assert!(valid_forbid.validate().is_ok());
299 assert_eq!(valid_forbid.deontic_opcode, 0x12);
300 assert!(valid_forbid.is_defeater);
301 assert_eq!(valid_forbid.buffer_distance_m, 150.0);
302
303 let valid_permit = SpatialCovenantZoneDecl::new(
304 "urn:qualia:zone:perisher-resort-corridor",
305 "PermittedSkiCorridor",
306 OP_PERMIT, false, 0.0, 2,
307 );
308 assert!(valid_permit.validate().is_ok());
309
310 let invalid_opcode = SpatialCovenantZoneDecl::new("urn:qualia:zone:invalid", "Type", 0x00, false, 10.0, 1);
311 assert!(invalid_opcode.validate().is_err());
312
313 let empty_id = SpatialCovenantZoneDecl::new("", "ValidType", OP_FORBID, false, 10.0, 1);
314 assert!(empty_id.validate().is_err());
315
316 let empty_type = SpatialCovenantZoneDecl::new("urn:qualia:zone:test", "", OP_FORBID, false, 10.0, 1);
317 assert!(empty_type.validate().is_err());
318
319 let negative_buffer = SpatialCovenantZoneDecl::new("urn:qualia:zone:test", "ValidType", OP_FORBID, false, -5.0, 1);
320 assert!(negative_buffer.validate().is_err());
321 }
322
323 #[test]
324 fn test_geosparql_deontic_covenant_fixture_exists() {
325 let manifest_dir = env!("CARGO_MANIFEST_DIR");
326 let fixture_path = std::path::Path::new(manifest_dir)
327 .join("fixtures")
328 .join("geography")
329 .join("geosparql_deontic_covenant.vibe");
330 assert!(
331 fixture_path.exists(),
332 "Fixture geosparql_deontic_covenant.vibe must exist at {:?}",
333 fixture_path
334 );
335 }
336}