commandagi 0.6.10

The CommandAGI SDK for Rust: the platform client (agent threads, live sessions on a simulated world) and CommandAGI documents (a schematic, a 3D part …) declared as code. No dependencies.
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
//! THE ONTOLOGY'S OWN FILES IN RUST — worlds, device definitions, dashboards, geo projects and node graphs, written as
//! the elements their editors edit. The same elements, and the same documents, as the TypeScript SDK's `ontology.ts`
//! and the Python SDK's `ontology.py`:
//!
//! ```
//! use commandagi::design::ontology::*;
//!
//! fn document() -> El {
//!     world([
//!         unit().uid("arm").name("arm").device("../../devices/so-101/definition.tsx").position([0, 0, 0]).rotation(0),
//!     ])
//!     .name("Shop")
//! }
//! # commandagi::design::declare(document()).unwrap();
//! ```
//!
//! A record is an element and its fields are the element's attributes, verbatim; a list of records is the parent's
//! children (`units` → `unit()`, `channels` → `channel()`). The tags:
//!
//! ```text
//! world([…]).name.description?.from?.model?          world.rs             space().origin_mm.size_mm, group().uid …,
//!   .links?.policies?                                                     unit().uid …, view(),
//!                                                                         interlock().name.unit.channel.requires.why
//! device([…]).name … .firmware?.revision?            definition.rs        channel().id.dir.medium.format.transport …,
//!                                                                         bound().channel.field.min?.max?.max_rate?
//!                                                                         .max_speed?, interlock().name.channel
//!                                                                         .requires.why.verbs?.when?
//! dashboard([…]).name …                              <name>.dashboard.rs  param().id.type_ …, one layout: split([a, b])
//!                                                                         .axis.ratio of two split|pane().id.kind …, or
//!                                                                         one pane() (repeat("live-stream"): one pane
//!                                                                         per live stream); region().side.tab …
//! geoproject([…]).id.name …                          <name>.geo.rs        date_range().start.end, camera(), reference()
//! shock([…]).id.name.event_type.targets.start …      <name>.shock.rs      reference()
//! scenario([…]).id.name.baseline_date.events …       <name>.scenario.rs   reference()
//! geomodel([…]).id.name.runtime.version …            <name>.geomodel.rs   parameter().name.default.min.max.label?,
//!                                                                         reference()
//! geoparams([…]).id.name.for_model.values            <name>.geoparams.rs  reference()
//! geolayer([…]).id.name.renderer.category.scale …    <name>.geolayer.rs   reference()
//! geoformula([…]).id.name.inputs.expression …        <name>.geoformula.rs reference()
//! geoview([…]).id.name.camera.timeline …             <name>.geoview.rs    reference()
//! georeport([…]).id.name.blocks                      <name>.georeport.rs  reference()
//! geograph([…]).id.name.nodes.edges                  <name>.geograph.rs   reference()
//! opgraph([…]).name                                  <name>.opgraph.rs    node().id.type_.x.y …ports, wire().from.to
//! ```
//!
//! A field whose own name has an underscore (a world's `origin_mm`, `size_mm`, a definition's `record_hz`) is its
//! method as it is. A node graph is the editor's op graph itself: `node().id("blur").type_("blur").x(300).y(80)
//! .radius(6)` is the node `{"id": "blur", "type": "blur", "inputs": {"radius": 6}, "meta": {"x": 300, "y": 80}}`, and
//! `wire().from("gradient:out").to("blur:in")` the wire into its `in` port; `.output(true)` marks a terminal. A port
//! whose name is not an attribute name (`layers.3`) is written in `.inputs(json(r#"{"layers.3": null}"#))`.
//!
//! [`OntologyAttrs`] has a method for each field the ontology's files and the shipped definitions use. A field it has
//! no method for (a port of a node type of your own) is set by [`El::attr`], which takes any name:
//! `node().id("blur").attr("cutoff", 4)`.
//!
//! A run gives back what the TypeScript SDK gives: for a world, a definition, a dashboard and a geo project, the
//! document (`{format, document, sources}`, each element's site keyed by its tree path) beside an empty graph; for a
//! node graph, the editor's own op graph, each node with `meta.source` and each wire's site in its target's
//! `meta.sources["wire:<port>"]`. A code form declares; it never enforces: the host reads a definition's bounds.
//!
//! Bounds and interlocks are what the host's admission gate holds every command to, driver or not (docs/devices.md §
//! the admission gate). A `bound()` names its channel and a field the channel's commands set; it folds into that
//! channel's `bounds`. An `interlock()` refuses a command on its `channel` unless each of `requires` holds on another
//! channel's last known state, and an unknown state refuses. A world's `interlock()` names the unit it guards (`unit`):
//! `bound().channel("joints").field("fr3_joint1").min(-2.9007).max(2.9007).max_rate(2.62)`.

use super::documents::{declare_document, js_string, tree_of_element, DocTree, TagRule, Vocabulary};
use super::element::{attributes, elements, rust_name};
use super::{Declared, Family};
pub use super::{fragment, json, El, Json, Value};

elements! {
    /// A world: its space, its units and its view.
    world: children;
    /// A world's space: `.origin_mm([…]).size_mm([…])`.
    space: leaf;
    /// What units stand in: a shelf level, a bench, a rack, a desk (`.uid("shelf-2").name(…).group(…)`).
    group: leaf;
    /// A unit placed in a world: `.uid("arm").name("arm").device("…/definition.tsx")`.
    unit: leaf;
    /// A world's view.
    view: leaf;
    /// Refused in a world: its twin steps its model's scene, and a simulation's scene is a `.3d.rs`'s.
    scene: children;
    /// A body of a refused `scene()`.
    body: leaf;
    /// A device definition: its channels.
    device: children;
    /// A channel of a device or a firmware (`firmware::firmware`): `.id("joints").dir("duplex").medium("records")`.
    channel: leaf;
    /// A bound of a channel of a device: `.channel("joints").field("fr3_joint1").min(-2.9).max(2.9).max_rate(2.62)`.
    bound: leaf;
    /// An interlock of a device or a world: `.name("…").channel("shuttle").requires(json(…)).why("…")`.
    interlock: leaf;
    /// A dashboard: its params, its one layout, its regions.
    dashboard: children;
    /// A dashboard's param: `.id("log").type_("file")`.
    param: leaf;
    /// A split of a dashboard's layout: two sides, each a split or a pane; `.axis("x").ratio(0.5)`.
    split: children;
    /// A pane of a dashboard's layout: `.id("scene").kind("world")`.
    pane: leaf;
    /// A region of a dashboard: `.side("left").tab("explorer")`.
    region: leaf;
    /// A geo project's manifest.
    geoproject: children;
    /// A geo project's date range: `.start("2015-01").end("2030-01")`.
    date_range = "dateRange": leaf;
    /// A geo project's camera.
    camera: leaf;
    /// A file a geo project names: `.role("layer").path("…")`.
    reference: leaf;
    /// A geo project's shock: `.id("closure").event_type("route-disruption").targets(json(…)).start("2028-03")`.
    shock: children;
    /// A geo project's scenario: the shocks, models and parameter sets it runs, by their paths.
    scenario: children;
    /// A geo project's model: its runtime and its parameters.
    geomodel: children;
    /// A parameter of a geo model: `.name("priceElasticity").default(0.3).min(0.1).max(1)`.
    parameter: leaf;
    /// A geo project's parameter set: `.for_model("commodity-shock").values(json(…))`.
    geoparams: children;
    /// A geo project's layer: `.renderer("point").category("Energy").source_dataset("…").scale(json(…))`.
    geolayer: children;
    /// A geo project's formula: `.inputs(json(…)).expression("industrial / gdp").output_unit("share of GDP")`.
    geoformula: children;
    /// A geo project's saved view: its camera, the layers drawn, a selection, a time and a comparison.
    geoview: children;
    /// A geo project's report: `.blocks(json(…))`, its prose and refs in order.
    georeport: children;
    /// A geo project's graph: `.nodes(json(…)).edges(json(…))`.
    geograph: children;
    /// A node graph: its nodes and wires.
    opgraph: children;
    /// A node of a node graph: `.id("blur").type_("blur").x(300).y(80)`, its ports' values beside.
    node: leaf;
    /// A wire of a node graph: `.from("gradient:out").to("blur:in")`.
    wire: leaf;
}

attributes! {
    /// The fields of the ontology's records, chained on their elements.
    pub trait OntologyAttrs {
        // A world's, a unit's and a body's.
        name; kind; description; from; model; uid; device; serial; revision; domain; support; channels; manual_url; position; rotation;
        origin_mm = "origin_mm"; size_mm = "size_mm"; dimensions_mm = "dimensions_mm";
        hz; at; rot; vel; shape; mass; friction; restitution; angular_damping = "angular_damping"; gravity; scale;
        backdrop; walls; grids; bodies; forces; particles; entities; relations; systems; robots; joints; links; kinematics;
        dynamics; constraints; fidelity; motion; color; blend; balance; coupled; seals; release; calibration; optics; root; policies;
        // A definition's and a channel's.
        id; type_; label; dir; medium; format; transport; interface; manufacturer; model_number = "model_number";
        product_url = "product_url"; price_usd = "price_usd"; record_hz = "record_hz"; spec_check = "spec_check";
        limits; min_interval_ms; verbs; units; unit; rate; baud; dialect; encoding; conversion; parameters; params; editor;
        /// A G-code channel's rapid rate (mm/min): what the simulator moves a G0 at.
        rapid_mm_per_min;
        /// The firmware a definition runs (a ref to its project folder, or a release `sha256:<hex>`); its `revision`
        /// is the hardware revision it is.
        firmware;
        notes; status; suggest; speed; source; title; value; rank;
        // A bound's and an interlock's.
        channel; field; min; max; max_rate; max_speed; requires; when; why;
        // A dashboard's, a param's, a pane's and a region's.
        focus; accept; default; required; axis; ratio; side; tab; open; collapsed; selected; path; view; world; param;
        file; group; pad;
        // A geo project's.
        created_at; updated_at; default_workspace; metadata; start; end; center_lat; center_lng; zoom; pitch; bearing;
        role; hash;
        // A geo project's shock's, scenario's, model's and parameter set's.
        event_type; targets; duration_months; magnitude; probability; implementation_lag_months; enabled; affected_variables;
        transmission_channels; baseline_date; time_horizon; parent_scenario; events; models; parameter_sets; tags; runtime;
        version; compatible_events; assumptions; limitations; citations; validation; for_model; values;
        // A geo project's layer's, formula's, view's, report's and graph's.
        renderer; category; source_dataset; source_formula; opacity; visible; filter; normalize_by; zoom_range; expression;
        output_unit; missing_value; camera; enabled_layers; layer_overrides; selection; timeline; comparison; blocks; nodes;
        edges;
        // A node graph's and a node's (the ports of the node-graph editor's own node types are fields too).
        meta; inputs; output; disabled; x; y; to; shade_a; shade_b; angle; seed; density; radius; freq; octave;
    }
}

pub(crate) const FAMILY: Family =
    Family { module: "ontology", roots: &["world", "device", "dashboard", "geoproject", "shock", "scenario", "geomodel", "geoparams", "geolayer", "geoformula", "geoview", "georeport", "geograph", "opgraph"], declare };

/// The graph id and domain a node graph has unless its file says another (the node-graph editor's new graph).
pub const NODE_GRAPH_ID: &str = "nodegraph";
/// The fields of a unit in a world's file (packages/domain/world/worlds.js). `serial`: the serial number of the one physical
/// thing a unit is; `revision`: its hardware revision (a firmware release says which it supports); `calibration`: a ref to the
/// unit's own `.calibration.rs` (its joints' zeros and gains, and its re-zeros).
pub const UNIT_FIELDS: &[&str] = &["uid", "name", "device", "serial", "revision", "domain", "group", "size_mm", "support", "channels", "manualUrl", "position", "rotation", "tilt_deg", "release", "calibration", "inputs", "equipment_id"];
/// The fields of a group in a world's file: what one unit stands in. `group` nests a group in another (a shelf holds its
/// levels); `size_mm` with `position` and `rotation` is the box the world view draws. A group has no device and no
/// channel: nothing runs or is granted on it.
pub const GROUP_FIELDS: &[&str] = &["uid", "name", "description", "group", "size_mm", "position", "rotation"];
/// `links`: the parts of the world's model that a run moves (packages/domain/world/pose.js modelPose), a definition's
/// link grammar with the unit named in each joint and emit; `node` is the id of the model's feature that makes the part.
/// `policies`: the world's follow policies (docs/follow.md): one unit's robot follows another's joints, by angle.
const WORLD_FIELDS: &[&str] = &["name", "description", "from", "model", "links", "policies"];
/// What a world reads: its fields, and `kind`, read only to refuse it by name (every world is real).
const WORLD_READ: &[&str] = &["name", "description", "from", "model", "links", "policies", "kind"];
const WORLD_KIND: &str = "a world names real things: it has no kind; a simulation is a run of a .3d.tsx";
const WORLD_SCENE: &str = "a world declares no scene: its twin steps its model's scene (model=\"model.3d.tsx\"), and a simulation's scene is a .3d.tsx's";
/// A `bound()`'s attributes: the channel it bounds, the field, and its limits.
const BOUND_FIELDS: &[&str] = &["channel", "field", "min", "max", "maxRate", "maxSpeed", "why"];
/// An `interlock()`'s attributes in a world; a definition's names no `unit`.
const INTERLOCK_FIELDS: &[&str] = &["name", "unit", "channel", "verbs", "when", "requires", "why"];
const DEVICE_INTERLOCK_FIELDS: &[&str] = &["name", "channel", "verbs", "when", "requires", "why"];
const GEO_FIELDS: &[&str] = &["id", "name", "createdAt", "updatedAt", "description", "defaultWorkspace", "metadata"];
/// A node's attributes that are not its ports.
const NODE_ATTRS: &[&str] = &["id", "type", "label", "x", "y", "disabled", "output", "meta", "inputs"];
const DASHBOARD_STRUCTURE: &[&str] = &["format", "layout", "panes", "params", "regions"];

const WORLD: Vocabulary = Vocabulary {
    format: "world",
    noun: "a world",
    root: "world",
    tags: &[
        TagRule::new("world", &[]).required(&["name"]).attrs(WORLD_READ),
        TagRule::new("space", &["world"]).single().required(&["origin_mm", "size_mm"]).attrs(&["origin_mm", "size_mm"]),
        TagRule::new("group", &["world"]).key("uid").required(&["uid", "name"]).attrs(GROUP_FIELDS),
        TagRule::new("unit", &["world"]).key("uid").required(&["uid", "name", "device"]).attrs(UNIT_FIELDS),
        TagRule::new("view", &["world"]).single(),
        TagRule::new("scene", &["world"]),
        TagRule::new("body", &["scene"]),
        TagRule::new("interlock", &["world"]).key("name").required(&["name", "unit", "channel", "requires", "why"]).attrs(INTERLOCK_FIELDS),
    ],
    from_tree: world_of,
};

const DEVICE: Vocabulary = Vocabulary {
    format: "device",
    noun: "a device definition",
    root: "device",
    tags: &[
        TagRule::new("device", &[]).required(&["name"]),
        TagRule::new("channel", &["device"]).key("id").required(&["id"]),
        TagRule::new("bound", &["device"]).required(&["channel", "field"]).attrs(BOUND_FIELDS),
        TagRule::new("interlock", &["device"]).key("name").required(&["name", "channel", "requires", "why"]).attrs(DEVICE_INTERLOCK_FIELDS),
    ],
    from_tree: device_of,
};

const DASHBOARD: Vocabulary = Vocabulary {
    format: "dashboard",
    noun: "a dashboard",
    root: "dashboard",
    tags: &[
        TagRule::new("dashboard", &[]).required(&["name"]),
        TagRule::new("param", &["dashboard"]).key("id").required(&["id", "type"]),
        TagRule::new("split", &["dashboard", "split"]).required(&["axis", "ratio"]).attrs(&["axis", "ratio"]),
        TagRule::new("pane", &["dashboard", "split"]).key("id").required(&["id"]),
        TagRule::new("region", &["dashboard"]).key("side").required(&["side"]),
    ],
    from_tree: dashboard_of,
};

const GEO: Vocabulary = Vocabulary {
    format: "geo",
    noun: "a geo project",
    root: "geoproject",
    tags: &[
        TagRule::new("geoproject", &[]).required(&["id", "name"]).attrs(GEO_FIELDS),
        TagRule::new("dateRange", &["geoproject"]).single().required(&["start", "end"]),
        TagRule::new("camera", &["geoproject"]).single(),
        TagRule::new("reference", &["geoproject"]).key("path").required(&["role", "path"]).attrs(&["role", "path", "hash"]),
    ],
    from_tree: geo_of,
};

/// What a geo document says of itself. Its times are the file's own: the code holds none.
const GEO_OWN: &[&str] = &["id", "name", "metadata"];
const SHOCK_DATA: &[&str] = &["eventType", "targets", "start", "durationMonths", "magnitude", "probability", "implementationLagMonths", "enabled", "affectedVariables", "transmissionChannels", "notes"];
const SCENARIO_DATA: &[&str] = &["baselineDate", "timeHorizon", "parentScenario", "events", "models", "parameterSets", "tags"];
const GEOMODEL_DATA: &[&str] = &["runtime", "version", "compatibleEvents", "assumptions", "limitations", "citations", "validation"];
const GEOPARAMS_DATA: &[&str] = &["forModel", "values"];
const GEOLAYER_DATA: &[&str] = &["renderer", "category", "sourceDataset", "sourceFormula", "scale", "opacity", "visible", "units", "filter", "normalizeBy", "zoomRange"];
const GEOFORMULA_DATA: &[&str] = &["inputs", "expression", "outputUnit", "missingValue"];
const GEOVIEW_DATA: &[&str] = &["camera", "enabledLayers", "layerOverrides", "selection", "timeline", "comparison"];
const GEOREPORT_DATA: &[&str] = &["blocks"];
const GEOGRAPH_DATA: &[&str] = &["nodes", "edges"];

/// A geo document whose fields are all attributes, with `<reference>` children (the root's attributes are given whole).
macro_rules! geo_document {
    ($name:ident, $format:literal, $noun:literal, $attrs:expr, $of:ident, $type_:literal, $data:ident) => {
        const $name: Vocabulary = Vocabulary {
            format: $format,
            noun: $noun,
            root: $format,
            tags: &[
                TagRule::new($format, &[]).required(&["id", "name"]).attrs($attrs),
                TagRule::new("reference", &[$format]).key("path").required(&["role", "path"]).attrs(&["role", "path", "hash"]),
            ],
            from_tree: $of,
        };
        fn $of(t: &DocTree) -> Result<Json, String> {
            geo_file_of(t, $type_, $data, None)
        }
    };
}

geo_document!(GEOLAYER, "geolayer", "a geo layer", &["id", "name", "metadata", "renderer", "category", "sourceDataset", "sourceFormula", "scale", "opacity", "visible", "units", "filter", "normalizeBy", "zoomRange"], geolayer_of, "geoeconomics/layer", GEOLAYER_DATA);
geo_document!(GEOFORMULA, "geoformula", "a geo formula", &["id", "name", "metadata", "inputs", "expression", "outputUnit", "missingValue"], geoformula_of, "geoeconomics/formula", GEOFORMULA_DATA);
geo_document!(GEOVIEW, "geoview", "a geo view", &["id", "name", "metadata", "camera", "enabledLayers", "layerOverrides", "selection", "timeline", "comparison"], geoview_of, "geoeconomics/view", GEOVIEW_DATA);
geo_document!(GEOREPORT, "georeport", "a geo report", &["id", "name", "metadata", "blocks"], georeport_of, "geoeconomics/report", GEOREPORT_DATA);
geo_document!(GEOGRAPH, "geograph", "a geo graph", &["id", "name", "metadata", "nodes", "edges"], geograph_of, "geoeconomics/graph", GEOGRAPH_DATA);

const SHOCK: Vocabulary = Vocabulary {
    format: "shock",
    noun: "a shock",
    root: "shock",
    tags: &[
        TagRule::new("shock", &[]).required(&["id", "name"]).attrs(&["id", "name", "metadata", "eventType", "targets", "start", "durationMonths", "magnitude", "probability", "implementationLagMonths", "enabled", "affectedVariables", "transmissionChannels", "notes"]),
        TagRule::new("reference", &["shock"]).key("path").required(&["role", "path"]).attrs(&["role", "path", "hash"]),
    ],
    from_tree: shock_of,
};

const SCENARIO: Vocabulary = Vocabulary {
    format: "scenario",
    noun: "a scenario",
    root: "scenario",
    tags: &[
        TagRule::new("scenario", &[]).required(&["id", "name"]).attrs(&["id", "name", "metadata", "baselineDate", "timeHorizon", "parentScenario", "events", "models", "parameterSets", "tags"]),
        TagRule::new("reference", &["scenario"]).key("path").required(&["role", "path"]).attrs(&["role", "path", "hash"]),
    ],
    from_tree: scenario_of,
};

const GEOMODEL: Vocabulary = Vocabulary {
    format: "geomodel",
    noun: "a geo model",
    root: "geomodel",
    tags: &[
        TagRule::new("geomodel", &[]).required(&["id", "name"]).attrs(&["id", "name", "metadata", "runtime", "version", "compatibleEvents", "assumptions", "limitations", "citations", "validation"]),
        TagRule::new("parameter", &["geomodel"]).key("name").required(&["name", "default", "min", "max"]).attrs(&["name", "label", "default", "min", "max"]),
        TagRule::new("reference", &["geomodel"]).key("path").required(&["role", "path"]).attrs(&["role", "path", "hash"]),
    ],
    from_tree: geomodel_of,
};

const GEOPARAMS: Vocabulary = Vocabulary {
    format: "geoparams",
    noun: "a geo parameter set",
    root: "geoparams",
    tags: &[
        TagRule::new("geoparams", &[]).required(&["id", "name"]).attrs(&["id", "name", "metadata", "forModel", "values"]),
        TagRule::new("reference", &["geoparams"]).key("path").required(&["role", "path"]).attrs(&["role", "path", "hash"]),
    ],
    from_tree: geoparams_of,
};

const OPGRAPH: Vocabulary = Vocabulary {
    format: "opgraph",
    noun: "a node graph",
    root: "opgraph",
    tags: &[
        TagRule::new("opgraph", &[]).attrs(&["id", "name", "domain", "meta"]),
        TagRule::new("node", &["opgraph"]).key("id").required(&["id", "type"]),
        TagRule::new("wire", &["opgraph"]).key("to").required(&["from", "to"]).attrs(&["from", "to"]),
    ],
    from_tree: opgraph_of,
};

/// The vocabularies of the ontology's files.
pub const ONTOLOGY: &[&Vocabulary] = &[&WORLD, &DEVICE, &DASHBOARD, &GEO, &SHOCK, &SCENARIO, &GEOMODEL, &GEOPARAMS, &GEOLAYER, &GEOFORMULA, &GEOVIEW, &GEOREPORT, &GEOGRAPH, &OPGRAPH];

/// Declare a world, a definition, a dashboard or a geo project (a document), or a node graph (a graph).
fn declare(root: El) -> Result<Declared, String> {
    if root.tag == "opgraph" {
        return Ok(Declared::Graph(opgraph_of(&tree_of_element(&root, &OPGRAPH)?)?));
    }
    let v = ONTOLOGY.iter().find(|v| v.root == root.tag).expect("a root of this family");
    declare_document(&root, v)
}

// ── Records ────────────────────────────────────────────────────────────────────────────────────────────────────────

/// The fields of `o` named in `keys`, in the order of `keys`.
fn own(o: &[(String, Json)], keys: &[&str]) -> Vec<(String, Json)> {
    keys.iter().filter_map(|k| o.iter().find(|(n, _)| n == k).cloned()).collect()
}

/// The fields of `o` but those named in `keys`.
fn omit(o: &[(String, Json)], keys: &[&str]) -> Vec<(String, Json)> {
    o.iter().filter(|(k, _)| !keys.contains(&k.as_str())).cloned().collect()
}

fn kids<'a>(t: &'a DocTree, tag: &'a str) -> impl Iterator<Item = &'a DocTree> {
    t.children.iter().filter(move |c| c.tag == tag)
}

/// A value as a message shows it: its JSON text (JavaScript's `JSON.stringify`).
fn text(v: Option<&Json>) -> String {
    v.map(Json::text).unwrap_or_else(|| "undefined".into())
}

fn is_record(v: Option<&Json>) -> bool {
    matches!(v, Some(Json::Obj(_)))
}

/// How a message names an element: its call with the attribute that names it (`node().id("a")`).
fn call(t: &DocTree, key: &str) -> String {
    let f = super::element::fn_name(t.tag);
    match t.attr_of(key) {
        Some(v @ Json::Str(_)) => format!("{f}().{}({})", rust_name(key), v.text()),
        _ => format!("{f}()"),
    }
}

// ── world.rs ───────────────────────────────────────────────────────────────────────────────────────────────────────

fn world_of(t: &DocTree) -> Result<Json, String> {
    if t.attr_of("kind").is_some() {
        return Err(format!("world().kind: {WORLD_KIND}"));
    }
    if kids(t, "scene").next().is_some() {
        return Err(format!("scene() in a world(): {WORLD_SCENE}"));
    }
    let mut out = Json::Obj(own(&t.attrs, WORLD_FIELDS));
    if let Some(space) = t.single("space") {
        out.set("space", space.record());
    }
    let groups: Vec<Json> = kids(t, "group").map(DocTree::record).collect();
    if !groups.is_empty() {
        out.set("groups", Json::Arr(groups));
    }
    out.set("units", Json::Arr(kids(t, "unit").map(DocTree::record).collect()));
    if let Some(view) = t.single("view") {
        out.set("view", view.record());
    }
    let interlocks: Vec<Json> = kids(t, "interlock").map(DocTree::record).collect();
    if !interlocks.is_empty() {
        out.set("interlocks", Json::Arr(interlocks));
    }
    Ok(out)
}

// ── definition.rs ──────────────────────────────────────────────────────────────────────────────────────────────────

fn device_of(t: &DocTree) -> Result<Json, String> {
    if t.attr_of("channels").is_some() {
        return Err("device(): write each channel as a channel() element, not a channels attribute".into());
    }
    if t.attr_of("interlocks").is_some() {
        return Err("device(): write each interlock as an interlock() element, not an interlocks attribute".into());
    }
    let mut channels: Vec<Json> = kids(t, "channel").map(DocTree::record).collect();
    if let Some(c) = channels.iter().find(|c| c.get("bounds").is_some()) {
        let id = text(c.get("id"));
        return Err(format!("channel().id({id}): write each bound as a bound().channel({id}) element, not a bounds attribute"));
    }
    for b in kids(t, "bound") {
        let Some(c) = channels.iter_mut().find(|c| c.get("id") == b.attr_of("channel")) else {
            return Err(format!("bound().field({}): channel {} is not a channel() of this device", text(b.attr_of("field")), text(b.attr_of("channel"))));
        };
        let bound = Json::Obj(omit(&b.attrs, &["channel"]));
        match c.get("bounds") {
            Some(Json::Arr(list)) => {
                let mut list = list.clone();
                list.push(bound);
                c.set("bounds", Json::Arr(list));
            }
            _ => {
                c.set("bounds", Json::Arr(vec![bound]));
            }
        }
    }
    let interlocks: Vec<Json> = kids(t, "interlock").map(DocTree::record).collect();
    let mut out = t.record();
    if !channels.is_empty() {
        out.set("channels", Json::Arr(channels));
    }
    if !interlocks.is_empty() {
        out.set("interlocks", Json::Arr(interlocks));
    }
    Ok(out)
}

// ── <name>.dashboard.rs ────────────────────────────────────────────────────────────────────────────────────────────

fn dashboard_of(t: &DocTree) -> Result<Json, String> {
    if let Some(k) = DASHBOARD_STRUCTURE.iter().find(|k| t.attr_of(k).is_some()) {
        return Err(format!("dashboard(): {k} is written as elements (param(), split(), pane(), region()), not an attribute"));
    }
    let is_layout = |c: &&DocTree| c.tag == "split" || c.tag == "pane";
    let layouts: Vec<&DocTree> = t.children.iter().filter(is_layout).collect();
    if layouts.len() != 1 {
        return Err(format!("dashboard() has one layout: a split() or one pane() (it has {})", layouts.len()));
    }
    fn layout(n: &DocTree, panes: &mut Vec<(String, Json)>) -> Result<Json, String> {
        if n.tag == "pane" {
            let id = js_string(n.attr_of("id"));
            if panes.iter().any(|(k, _)| *k == id) {
                return Err(format!("two pane() have id {:?}", id));
            }
            // A repeating pane is one pane per live stream (the shell grows it): it is what it repeats, never a file.
            let pane = omit(&n.attrs, &["id"]);
            let repeated = pane.iter().find(|(k, _)| k == "repeat").map(|(_, v)| v.clone());
            if let Some(what) = repeated {
                let files = pane.iter().any(|(k, v)| k == "kind" && *v == Json::Str("files".into()));
                let names = pane.iter().any(|(k, _)| k == "selected" || k == "path");
                if what != Json::Str("live-stream".into()) || !files || names {
                    return Err(format!("pane().id({:?}): repeat is \"live-stream\", and a repeating pane shows files and names no file of its own (it is filled from what is live)", id));
                }
            }
            panes.push((id.clone(), Json::Obj(pane)));
            return Ok(Json::obj().with("kind", "leaf").with("paneId", id));
        }
        let sides: Vec<&DocTree> = n.children.iter().filter(|c| c.tag == "split" || c.tag == "pane").collect();
        if sides.len() != 2 {
            return Err(format!("a split() has two sides (this one has {})", sides.len()));
        }
        let children = sides.into_iter().map(|c| layout(c, panes)).collect::<Result<Vec<_>, _>>()?;
        let attr = |k: &str| n.attr_of(k).cloned().unwrap_or(Json::Null);
        Ok(Json::obj().with("kind", "split").with("axis", attr("axis")).with("ratio", attr("ratio")).with("children", children))
    }
    let mut panes = Vec::new();
    let root = layout(layouts[0], &mut panes)?;
    let params: Vec<Json> = kids(t, "param").map(DocTree::record).collect();
    let mut regions = Json::obj();
    for r in kids(t, "region") {
        regions.set(&js_string(r.attr_of("side")), Json::Obj(omit(&r.attrs, &["side"])));
    }
    let mut out = Json::obj().with("format", "commandagi-dashboard");
    for (k, v) in &t.attrs {
        out.set(k, v.clone());
    }
    if !params.is_empty() {
        out.set("params", Json::Arr(params));
    }
    out.set("layout", root);
    out.set("panes", Json::Obj(panes));
    if regions != Json::obj() {
        out.set("regions", regions);
    }
    Ok(out)
}

// ── <name>.geo.rs (the geo project's manifest) ─────────────────────────────────────────────────────────────────────

fn geo_of(t: &DocTree) -> Result<Json, String> {
    let mut top = Json::Obj(own(&t.attrs, GEO_FIELDS));
    let description = top.remove("description");
    let workspace = top.remove("defaultWorkspace");
    let mut data = Json::obj();
    if let Some(w) = workspace {
        data.set("defaultWorkspace", w);
    }
    if let Some(range) = t.single("dateRange") {
        data.set("defaultDateRange", range.record());
    }
    if let Some(camera) = t.single("camera") {
        data.set("defaultCamera", camera.record());
    }
    if let Some(d) = description {
        data.set("description", d);
    }
    // The geo project's manifest says which shape it is in; this is the one the studio reads.
    let mut out = Json::obj().with("type", "geoeconomics/project").with("schemaVersion", "1.0");
    if let Json::Obj(fields) = top {
        for (k, v) in fields {
            out.set(&k, v);
        }
    }
    let refs: Vec<Json> = kids(t, "reference").map(DocTree::record).collect();
    if !refs.is_empty() {
        out.set("references", Json::Arr(refs));
    }
    Ok(out.with("data", data))
}

// ── a geo project's documents: <name>.shock.rs, .scenario.rs, .geomodel.rs, .geoparams.rs ───────────────────────────

/// A geo document's envelope: its own fields, its references, and its `data` (with a keyed record's children folded in).
fn geo_file_of(t: &DocTree, type_: &str, fields: &[&str], record: Option<(&str, &str, &str)>) -> Result<Json, String> {
    // A geo document says which shape it is in; this is the one the studio reads.
    let mut out = Json::obj().with("type", type_).with("schemaVersion", "1.0");
    for (k, v) in own(&t.attrs, GEO_OWN) {
        out.set(&k, v);
    }
    let refs: Vec<Json> = kids(t, "reference").map(DocTree::record).collect();
    if !refs.is_empty() {
        out.set("references", Json::Arr(refs));
    }
    let mut data = Json::Obj(own(&t.attrs, fields));
    if let Some((tag, field, key)) = record {
        let mut entries = Json::obj();
        let mut any = false;
        for e in kids(t, tag) {
            let mut r = e.record();
            if let Some(Json::Str(k)) = r.remove(key) {
                entries.set(&k, r);
                any = true;
            }
        }
        if any {
            data.set(field, entries);
        }
    }
    Ok(out.with("data", data))
}

fn shock_of(t: &DocTree) -> Result<Json, String> {
    geo_file_of(t, "geoeconomics/event", SHOCK_DATA, None)
}

fn scenario_of(t: &DocTree) -> Result<Json, String> {
    geo_file_of(t, "geoeconomics/scenario", SCENARIO_DATA, None)
}

fn geomodel_of(t: &DocTree) -> Result<Json, String> {
    geo_file_of(t, "geoeconomics/model", GEOMODEL_DATA, Some(("parameter", "parameterSchema", "name")))
}

fn geoparams_of(t: &DocTree) -> Result<Json, String> {
    geo_file_of(t, "geoeconomics/params", GEOPARAMS_DATA, None)
}

// ── <name>.opgraph.rs: the node graph ──────────────────────────────────────────────────────────────────────────────

/// Whether a port is written as a method of its node (else in `.inputs(json(…))`): `[A-Za-z_$][\w$-]*`, not a field.
pub fn port_is_attribute(port: &str) -> bool {
    let mut chars = port.chars();
    let first = chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_' || c == '$');
    first && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '$' | '-')) && !NODE_ATTRS.contains(&port) && port != "key" && port != "children"
}

fn is_wire(v: Option<&Json>) -> bool {
    match v.and_then(|v| v.get("wire")) {
        Some(w @ Json::Obj(_)) => matches!(w.get("node"), Some(Json::Str(_))) && matches!(w.get("port"), Some(Json::Str(_))),
        _ => false,
    }
}

/// `"gradient:out"` → (node, port): a node id has no colon; a port may have dots (`mix:layers.2`).
fn end_of(text: Option<&Json>, what: &str) -> Result<(String, String), String> {
    let split = match text {
        Some(Json::Str(s)) => s.split_once(':').filter(|(n, p)| !n.is_empty() && !p.is_empty() && !p.contains(['\n', '\r', '\u{2028}', '\u{2029}'])),
        _ => None,
    };
    match split {
        Some((node, port)) => Ok((node.to_string(), port.to_string())),
        None => Err(format!("wire(): {what} is \"node:port\", not {}", self::text(text))),
    }
}

fn opgraph_of(t: &DocTree) -> Result<Json, String> {
    let mut nodes: Vec<(String, Json)> = Vec::new();
    let mut outputs: Vec<Json> = Vec::new();
    for n in kids(t, "node") {
        let id = js_string(n.attr_of("id"));
        let at = call(n, "id");
        if !matches!(n.attr_of("type"), Some(Json::Str(s)) if !s.is_empty()) {
            return Err(format!("{at} needs a type_"));
        }
        if id.contains(':') {
            return Err(format!("{at}: an id has no colon (a wire names \"node:port\")"));
        }
        let mut inputs = Json::Obj(n.attrs.iter().filter(|(k, _)| !NODE_ATTRS.contains(&k.as_str())).cloned().collect());
        if let Some(given) = n.attr_of("inputs") {
            let Json::Obj(ports) = given else { return Err(format!("{at} inputs is an object of ports")) };
            for (k, v) in ports {
                if port_is_attribute(k) {
                    return Err(format!("{at}: write {k} as a method (.{}(…)), not in inputs", rust_name(k)));
                }
                inputs.set(k, v.clone());
            }
        }
        let mut meta = match n.attr_of("meta") {
            None => Json::obj(),
            Some(m @ Json::Obj(_)) => m.clone(),
            Some(_) => return Err(format!("{at} meta is an object")),
        };
        for k in ["x", "y"] {
            if let Some(v) = n.attr_of(k) {
                meta.set(k, v.clone());
            }
        }
        if let Some(s) = &n.source {
            meta.set("source", s.clone());
        }
        let mut node = Json::obj().with("id", id.as_str()).with("type", n.attr_of("type").cloned().unwrap_or(Json::Null));
        if let Some(label @ Json::Str(_)) = n.attr_of("label") {
            node.set("label", label.clone());
        }
        node.set("inputs", inputs);
        if n.attr_of("disabled") == Some(&Json::Bool(true)) {
            node.set("disabled", true);
        }
        if meta != Json::obj() {
            node.set("meta", meta);
        }
        if n.attr_of("output") == Some(&Json::Bool(true)) {
            outputs.push(Json::from(id.as_str()));
        }
        nodes.push((id, node));
    }
    for w in kids(t, "wire") {
        let (from_node, from_port) = end_of(w.attr_of("from"), "from")?;
        let (to_node, to_port) = end_of(w.attr_of("to"), "to")?;
        if !nodes.iter().any(|(k, _)| *k == to_node) {
            return Err(format!("wire().to({}): no node().id({})", text(w.attr_of("to")), Json::from(to_node).text()));
        }
        if !nodes.iter().any(|(k, _)| *k == from_node) {
            return Err(format!("wire().from({}): no node().id({})", text(w.attr_of("from")), Json::from(from_node).text()));
        }
        let target = &mut nodes.iter_mut().find(|(k, _)| *k == to_node).expect("checked").1;
        let literal = target.get("inputs").and_then(|i| i.get(&to_port)).cloned();
        if is_wire(literal.as_ref()) {
            return Err(format!("two wire() go into {to_node}:{to_port} (a port takes one wire)"));
        }
        let mut bound = Json::obj().with("wire", Json::obj().with("node", from_node).with("port", from_port));
        if let Some(v) = literal.filter(|v| *v != Json::Null) {
            bound.set("value", v);
        }
        if let Json::Obj(fields) = target {
            if let Some((_, inputs)) = fields.iter_mut().find(|(k, _)| k == "inputs") {
                inputs.set(&to_port, bound);
            }
        }
        // Where the wire was written (`meta.sources`, by `wire:<port>`): the editor finds the element again to remove it.
        if let Some(s) = &w.source {
            let mut meta = target.get("meta").cloned().unwrap_or_else(Json::obj);
            let mut sources = match meta.get("sources") {
                Some(o @ Json::Obj(_)) => o.clone(),
                _ => Json::obj(),
            };
            sources.set(&format!("wire:{to_port}"), s.clone());
            meta.set("sources", sources);
            target.set("meta", meta);
        }
    }
    let mut meta = if is_record(t.attr_of("meta")) { t.attr_of("meta").cloned().unwrap_or_else(Json::obj) } else { Json::obj() };
    if let Some(name) = t.attr_of("name") {
        meta.set("name", name.clone());
    }
    meta.set("domain", t.attr_of("domain").filter(|d| **d != Json::Null).cloned().unwrap_or_else(|| NODE_GRAPH_ID.into()));
    let id = match t.attr_of("id") {
        Some(Json::Str(s)) => s.clone(),
        _ => NODE_GRAPH_ID.to_string(),
    };
    Ok(Json::obj().with("id", id).with("nodes", Json::Obj(nodes)).with("outputs", outputs).with("meta", meta))
}