1use super::{EffectClass, HonestyLabel, SchemaArg, SchemaEntry};
11
12pub type CapabilitySchemaEntry = SchemaEntry;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub enum Effect {
18 Pure, Compute, Cold, Async, External,
19}
20
21impl Effect {
22 pub const fn as_str(&self) -> &'static str {
23 match self {
24 Self::Pure => "pure", Self::Compute => "compute", Self::Cold => "cold",
25 Self::Async => "async", Self::External => "external",
26 }
27 }
28}
29
30pub type EffectTag = Effect;
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
35pub enum ExecutionClass { PureCpu, InteractiveStudio, AsyncHost }
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
39pub enum DeterminismGuarantee { BitExactParity, PlatformAgnostic, DeterministicDigest }
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43pub enum SemanticUnit { Dimensionless, Meters, Radians, Degrees, Seconds, Bytes, Millimeters }
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
47pub enum ValueType { F32, F64, U32, U64, I32, I64, Bool, Str, Record, List, FieldRef, GeometryRef }
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
51pub enum StyleProfile { ThematicChoropleth, BivariateMatrix, DotDensity, VectorCadastral }
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
55pub enum StyleSupportLevel { Core, Optional, Emulated }
56
57#[allow(non_snake_case)]
58pub mod complex_Validation { pub use super::ComplexDecl; }
59pub mod host { pub use super::EffectTag; }
60pub mod intent { pub use super::{DeterminismGuarantee, ExecutionClass}; }
61pub mod semantic_types { pub use super::{SemanticUnit, ValueType}; }
62pub mod styles { pub use super::{StyleProfile, StyleSupportLevel}; }
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
66pub enum ParamType {
67 F64, I64, U64, Bool, Str, Record, List, FieldRef, GeometryRef,
68}
69
70impl ParamType {
71 pub const fn as_str(&self) -> &'static str {
72 match self {
73 Self::F64 => "f64", Self::I64 => "i64", Self::U64 => "u64", Self::Bool => "bool",
74 Self::Str => "string", Self::Record => "Record", Self::List => "List",
75 Self::FieldRef => "FieldRef", Self::GeometryRef => "GeometryRef",
76 }
77 }
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub struct ParamSchema {
83 pub name: &'static str,
84 pub param_type: ParamType,
85 pub required: bool,
86 pub description: &'static str,
87}
88
89const fn p(name: &'static str, ty: ParamType, req: bool, desc: &'static str) -> ParamSchema {
90 ParamSchema { name, param_type: ty, required: req, description: desc }
91}
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub struct GeoCartographyPoetSpec {
96 pub invoke_id: &'static str,
97 pub call_path: &'static str,
98 pub effect: Effect,
99 pub params: &'static [ParamSchema],
100 pub returns: &'static str,
101 pub description: &'static str,
102}
103
104const fn spec(
105 invoke_id: &'static str, call_path: &'static str, effect: Effect,
106 returns: &'static str, description: &'static str, params: &'static [ParamSchema],
107) -> GeoCartographyPoetSpec {
108 GeoCartographyPoetSpec { invoke_id, call_path, effect, params, returns, description }
109}
110
111#[derive(Debug, Clone, PartialEq)]
113pub struct ComplexDecl {
114 pub name: String,
115 pub complex_id: String,
116 pub states: Vec<String>,
117 pub transitions: Vec<String>,
118 pub invariants: Vec<String>,
119 pub initial_state: String,
120 pub target_state: String,
121}
122
123impl ComplexDecl {
124 pub fn new(
125 name: impl Into<String>, complex_id: impl Into<String>, states: Vec<String>,
126 transitions: Vec<String>, invariants: Vec<String>,
127 initial_state: impl Into<String>, target_state: impl Into<String>,
128 ) -> Self {
129 Self {
130 name: name.into(), complex_id: complex_id.into(), states, transitions,
131 invariants, initial_state: initial_state.into(), target_state: target_state.into(),
132 }
133 }
134
135 pub fn validate(&self) -> Result<(), &'static str> {
136 if self.name.is_empty() { return Err("name must not be empty"); }
137 if self.complex_id.is_empty() { return Err("complex_id must not be empty"); }
138 if self.states.is_empty() { return Err("states must not be empty"); }
139 if self.transitions.is_empty() { return Err("transitions must not be empty"); }
140 if !self.states.contains(&self.initial_state) { return Err("initial_state not in states"); }
141 if !self.states.contains(&self.target_state) { return Err("target_state not in states"); }
142 Ok(())
143 }
144}
145
146pub type CartographicPublicationComplexDecl = ComplexDecl;
148
149pub fn cartographic_publication_complex_decl() -> ComplexDecl {
151 ComplexDecl::new(
152 "CartographicPublicationComplex",
153 "urn:qualia:topology:cartographic-publication",
154 vec!["StudioAuthoring".into(), "TopologySnapped".into(), "ThematicClassified".into(), "CvdAccessibilityVerified".into(), "PublicationSvgExported".into()],
155 vec!["sync_terrain_and_topology".into(), "classify_jenks_bivariate".into(), "verify_cvd_wcag_contrast".into(), "export_publication_layout".into()],
156 vec!["CoWStrokeReversibility".into(), "ZeroSliverTopology".into(), "WcagAaContrastAdherence".into(), "DeterministicSvgDigest".into()],
157 "StudioAuthoring",
158 "PublicationSvgExported",
159 )
160}
161
162pub const GEO_CARTOGRAPHY_POET_INVOKE_IDS: &[&str] = &[
164 "PoetGeo.cow_stroke_apply",
165 "PoetGeo.cow_undo_redo",
166 "PoetGeo.shared_vertex_move_split",
167 "PoetGeo.geodesic_ruler_protractor",
168 "PoetGeo.orbital_camera_flythrough",
169 "PoetGeo.terrain_graph_intent_sync",
170 "Cartography.classify_jenks_thematic",
171 "Cartography.bivariate_choropleth_3x3",
172 "Cartography.proportional_dot_density",
173 "Cartography.simulate_cvd_palette",
174 "Cartography.audit_wcag_contrast",
175 "Cartography.compose_publication_svg",
176];
177
178pub const GEO_CARTOGRAPHY_POET_RAW: &[GeoCartographyPoetSpec] = &[
180 spec("PoetGeo.cow_stroke_apply", "poet_geo.cow_stroke_apply", Effect::Compute, "Record",
182 "Applies interactive Copy-on-Write brush sculpt stroke on raster/vector layers with localized dirty tile tracking.", &[
183 p("stroke_id", ParamType::Str, true, "Unique identifier for interactive brush stroke"),
184 p("tool_type", ParamType::Str, true, "Brush operator: raise, lower, smooth, terrace, or stamp"),
185 p("stroke_path", ParamType::List, true, "List of 3D/geodetic cursor waypoint coordinates [x, y, z]"),
186 p("brush_radius_m", ParamType::F64, true, "Brush spatial influence radius in meters"),
187 p("intensity", ParamType::F64, false, "Brush application intensity factor (0.0 to 1.0)"),
188 ]),
189 spec("PoetGeo.cow_undo_redo", "poet_geo.cow_undo_redo", Effect::Compute, "Record",
191 "Navigates non-destructive CoW undo/redo stroke journal with immutable tile-hash revision tree.", &[
192 p("session_id", ParamType::Str, true, "Active Poet interactive editing session identifier"),
193 p("action", ParamType::Str, true, "History traversal operation: undo, redo, or checkout_revision"),
194 p("steps", ParamType::U64, false, "Number of historical transaction steps to step backward or forward"),
195 ]),
196 spec("PoetGeo.shared_vertex_move_split", "poet_geo.shared_vertex_move_split", Effect::Compute, "Record",
198 "Moves or splits a shared topological vertex across adjacent parcel/polygon boundaries preserving zero-gap topology.", &[
199 p("target_vertex", ParamType::Record, true, "Source vertex coordinates and tolerance radius {x, y, crs}"),
200 p("destination", ParamType::Record, true, "New vertex coordinates {x, y}"),
201 p("split_edge", ParamType::Bool, false, "Split intersected polygon edges if new vertex lies on boundary"),
202 p("snap_tolerance_m", ParamType::F64, false, "Snapping tolerance distance in meters"),
203 ]),
204 spec("PoetGeo.geodesic_ruler_protractor", "poet_geo.geodesic_ruler_protractor", Effect::Pure, "Record",
206 "Computes interactive Karney geodesic distance, forward/reverse azimuths, and angular vertex protractor bearings.", &[
207 p("waypoints", ParamType::List, true, "Sequence of geodetic points [{lat, lon, height_m}]"),
208 p("ellipsoid", ParamType::Str, false, "Reference ellipsoid model (default GRS80/WGS84)"),
209 p("include_profile", ParamType::Bool, false, "Compute continuous terrain elevation profile along geodesic"),
210 ]),
211 spec("PoetGeo.orbital_camera_flythrough", "poet_geo.orbital_camera_flythrough", Effect::Pure, "Record",
213 "Generates cinematic Catmull-Rom or B-spline orbital 3D camera keyframes with terrain collision avoidance.", &[
214 p("keyframe_waypoints", ParamType::List, true, "Camera target path keypoints [{pos, target, fov, roll, duration_s}]"),
215 p("spline_mode", ParamType::Str, false, "Interpolation curve type: catmull_rom, b_spline, or centripetal"),
216 p("min_ground_clearance_m", ParamType::F64, false, "Minimum camera clearance height above elevation terrain"),
217 ]),
218 spec("PoetGeo.terrain_graph_intent_sync", "poet_geo.terrain_graph_intent_sync", Effect::Compute, "Record",
220 "Synchronizes live interactive Poet canvas edits with QualiaDB reactive IntentBus and topological graph ledger.", &[
221 p("intent_id", ParamType::Str, true, "Intent transaction identifier"),
222 p("layer_manifest", ParamType::Record, true, "Manifest describing affected terrain raster and vector layers"),
223 p("author_did", ParamType::Str, true, "Decentralized identifier DID of authoring agent or user"),
224 ]),
225 spec("Cartography.classify_jenks_thematic", "cartography.classify_jenks_thematic", Effect::Pure, "Record",
227 "Computes Jenks Natural Breaks optimization, quantiles, equal-interval, or standard-deviation thematic class limits.", &[
228 p("values", ParamType::List, true, "Numeric attribute sample series to classify"),
229 p("class_count", ParamType::U64, true, "Number of thematic output intervals/bins (e.g. 5 to 9)"),
230 p("method", ParamType::Str, false, "Classification algorithm: jenks_natural_breaks, quantile, equal_interval, or std_dev"),
231 ]),
232 spec("Cartography.bivariate_choropleth_3x3", "cartography.bivariate_choropleth_3x3", Effect::Pure, "Record",
234 "Generates a 2D 3x3 bivariate choropleth color matrix encoding two intersecting statistical variables simultaneously.", &[
235 p("var1_values", ParamType::List, true, "First numeric attribute distribution series (X-axis)"),
236 p("var2_values", ParamType::List, true, "Second numeric attribute distribution series (Y-axis)"),
237 p("color_scheme", ParamType::Str, true, "Bivariate palette scheme: pink_blue, purple_green, or brown_teal"),
238 p("var1_breaks", ParamType::List, false, "Explicit class cutoffs for variable 1"),
239 p("var2_breaks", ParamType::List, false, "Explicit class cutoffs for variable 2"),
240 ]),
241 spec("Cartography.proportional_dot_density", "cartography.proportional_dot_density", Effect::Compute, "Record",
243 "Synthesizes pseudo-random dot-density distributions within polygon boundaries with spatial exclusion masks.", &[
244 p("polygon_geometry", ParamType::GeometryRef, true, "Bounding polygon geometry reference or GeoJSON feature"),
245 p("attribute_total", ParamType::F64, true, "Total statistical quantity to distribute"),
246 p("unit_value_per_dot", ParamType::F64, true, "Value represented by each discrete dot symbol"),
247 p("exclusion_mask", ParamType::Record, false, "Waterbody or steep-slope exclusion mask preventing dot placement"),
248 ]),
249 spec("Cartography.simulate_cvd_palette", "cartography.simulate_cvd_palette", Effect::Pure, "Record",
251 "Simulates color vision deficiency (deuteranopia, protanopia, tritanopia, achromatopsia) on thematic palettes.", &[
252 p("palette_hex", ParamType::List, true, "List of sRGB hex color codes ['#1a9850', '#ffffbf', ...]"),
253 p("deficiency_type", ParamType::Str, true, "CVD model: deuteranopia, protanopia, tritanopia, or achromatopsia"),
254 p("severity", ParamType::F64, false, "Deficiency severity factor from 0.0 (normal) to 1.0 (complete)"),
255 ]),
256 spec("Cartography.audit_wcag_contrast", "cartography.audit_wcag_contrast", Effect::Pure, "Record",
258 "Audits WCAG 2.1 AA/AAA relative luminance contrast ratios for text, symbols, and adjacent map polygon boundaries.", &[
259 p("foreground_colors", ParamType::List, true, "List of foreground text/symbol hex colors"),
260 p("background_colors", ParamType::List, true, "List of background canvas/polygon hex colors"),
261 p("conformance_target", ParamType::Str, false, "WCAG conformance level: aa_normal, aa_large, or aaa"),
262 ]),
263 spec("Cartography.compose_publication_svg", "cartography.compose_publication_svg", Effect::Pure, "Record",
265 "Composes publication-ready cartographic SVG layout with neatline, graticule ticks, dynamic scale bar, north arrow, legend, and metadata.", &[
266 p("map_layers", ParamType::List, true, "Ordered list of styled vector/raster layer render directives"),
267 p("layout_dimensions", ParamType::Record, true, "Output canvas dimensions {width_mm, height_mm, dpi, margin_mm}"),
268 p("scale_bar", ParamType::Record, true, "Scale bar configuration {units, max_width_mm, divisions}"),
269 p("north_arrow", ParamType::Record, false, "North arrow graphic style and placement anchor"),
270 p("legend_config", ParamType::Record, false, "Legend swatch symbols, titles, and layout orientation"),
271 ]),
272];
273
274pub fn geo_cartography_poet_entries() -> Vec<CapabilitySchemaEntry> {
276 GEO_CARTOGRAPHY_POET_RAW.iter().map(|s| {
277 let effect_class = match s.effect {
278 Effect::Pure => EffectClass::Pure,
279 Effect::Compute | Effect::Cold => EffectClass::Read,
280 Effect::Async | Effect::External => EffectClass::External,
281 };
282 let mut entry = SchemaEntry::new(s.invoke_id, effect_class, HonestyLabel::Always, s.returns)
283 .with_description(s.description);
284 for p in s.params {
285 entry = entry.with_arg(SchemaArg::new(p.name, p.param_type.as_str(), p.required).with_description(p.description));
286 }
287 entry
288 }).collect()
289}
290
291pub fn entries() -> Vec<SchemaEntry> {
293 geo_cartography_poet_entries()
294}
295
296pub fn lookup_geo_cartography_poet_entry(call_path: &str) -> Option<CapabilitySchemaEntry> {
298 let s = GEO_CARTOGRAPHY_POET_RAW.iter().find(|s| s.call_path == call_path || s.invoke_id == call_path)?;
299 let effect_class = match s.effect {
300 Effect::Pure => EffectClass::Pure,
301 Effect::Compute | Effect::Cold => EffectClass::Read,
302 Effect::Async | Effect::External => EffectClass::External,
303 };
304 let mut entry = SchemaEntry::new(s.invoke_id, effect_class, HonestyLabel::Always, s.returns)
305 .with_description(s.description);
306 for p in s.params {
307 entry = entry.with_arg(SchemaArg::new(p.name, p.param_type.as_str(), p.required).with_description(p.description));
308 }
309 Some(entry)
310}
311
312pub fn lookup_geo_cartography_poet_spec(call_path: &str) -> Option<&'static GeoCartographyPoetSpec> {
314 GEO_CARTOGRAPHY_POET_RAW.iter().find(|s| s.call_path == call_path || s.invoke_id == call_path)
315}
316
317#[cfg(test)]
318mod tests {
319 use super::*;
320
321 #[test]
322 fn test_geo_cartography_poet_count_and_uniqueness() {
323 assert_eq!(GEO_CARTOGRAPHY_POET_RAW.len(), 12);
324 assert_eq!(GEO_CARTOGRAPHY_POET_INVOKE_IDS.len(), 12);
325 for (i, spec) in GEO_CARTOGRAPHY_POET_RAW.iter().enumerate() {
326 assert_eq!(spec.invoke_id, GEO_CARTOGRAPHY_POET_INVOKE_IDS[i]);
327 assert!(spec.invoke_id.starts_with("PoetGeo.") || spec.invoke_id.starts_with("Cartography."));
328 assert!(spec.call_path.starts_with("poet_geo.") || spec.call_path.starts_with("cartography."));
329 assert!(!spec.returns.is_empty());
330 assert!(!spec.description.is_empty());
331 }
332 let mut ids: Vec<&str> = GEO_CARTOGRAPHY_POET_INVOKE_IDS.to_vec();
333 ids.sort();
334 ids.dedup();
335 assert_eq!(ids.len(), 12, "All 12 invoke IDs must be unique");
336
337 let mut paths: Vec<&str> = GEO_CARTOGRAPHY_POET_RAW.iter().map(|s| s.call_path).collect();
338 paths.sort();
339 paths.dedup();
340 assert_eq!(paths.len(), 12, "All 12 call paths must be unique");
341 }
342
343 #[test]
344 fn test_entries_conversion_and_lookup() {
345 for id in GEO_CARTOGRAPHY_POET_INVOKE_IDS {
346 assert!(lookup_geo_cartography_poet_entry(id).is_some());
347 }
348 for spec in GEO_CARTOGRAPHY_POET_RAW {
349 assert!(lookup_geo_cartography_poet_entry(spec.call_path).is_some());
350 }
351 assert!(lookup_geo_cartography_poet_entry("Cartography.unknown_call").is_none());
352
353 let converted = geo_cartography_poet_entries();
354 assert_eq!(converted.len(), 12);
355 for (i, entry) in converted.iter().enumerate() {
356 assert_eq!(entry.id, GEO_CARTOGRAPHY_POET_INVOKE_IDS[i]);
357 assert_eq!(entry.honesty, HonestyLabel::Always);
358 }
359
360 let alias_entries = entries();
361 assert_eq!(alias_entries.len(), 12);
362
363 let spec_ref = lookup_geo_cartography_poet_spec("poet_geo.cow_stroke_apply");
364 assert!(spec_ref.is_some());
365 assert_eq!(spec_ref.unwrap().invoke_id, "PoetGeo.cow_stroke_apply");
366 }
367
368 #[test]
369 fn test_cartographic_publication_complex_decl_validation() {
370 let decl = cartographic_publication_complex_decl();
371 assert!(decl.validate().is_ok());
372 assert_eq!(decl.name, "CartographicPublicationComplex");
373 assert_eq!(decl.complex_id, "urn:qualia:topology:cartographic-publication");
374 assert_eq!(decl.states.len(), 5);
375 assert_eq!(decl.transitions.len(), 4);
376 assert_eq!(decl.invariants.len(), 4);
377 assert_eq!(decl.initial_state, "StudioAuthoring");
378 assert_eq!(decl.target_state, "PublicationSvgExported");
379
380 let bad_initial = ComplexDecl::new("C", "id", vec!["A".into()], vec!["t".into()], vec![], "NonExistent", "A");
381 assert!(bad_initial.validate().is_err());
382
383 let bad_target = ComplexDecl::new("C", "id", vec!["A".into()], vec!["t".into()], vec![], "A", "NonExistent");
384 assert!(bad_target.validate().is_err());
385
386 let empty_name = ComplexDecl::new("", "id", vec!["A".into()], vec!["t".into()], vec![], "A", "A");
387 assert!(empty_name.validate().is_err());
388 }
389
390 #[test]
391 fn test_poet_cartography_live_edit_fixture_exists() {
392 let manifest_dir = env!("CARGO_MANIFEST_DIR");
393 let fixture_path = std::path::Path::new(manifest_dir)
394 .join("fixtures")
395 .join("geography")
396 .join("poet_cartography_live_edit.vibe");
397 assert!(
398 fixture_path.exists(),
399 "Fixture poet_cartography_live_edit.vibe must exist at {:?}",
400 fixture_path
401 );
402 }
403}